I have the next mysql tables
CREATE TABLE IF NOT EXISTS `my_app`.`hotel` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NOT NULL,
`destination_id` INT NOT NULL,
PRIMARY KEY (`id`),
INDEX `idx_name` (`name` ASC),
INDEX `fk_hotel_destination1_idx` (`destination_id` ASC),
CONSTRAINT `fk_hotel_destination1`
FOREIGN KEY (`destination_id`)
REFERENCES `my_app`.`destination` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
CREATE TABLE IF NOT EXISTS `my_app`.`hotel_alias` (
`id` INT NOT NULL AUTO_INCREMENT,
`hotel_id` INT NOT NULL,
`name` VARCHAR(45) NOT NULL,
PRIMARY KEY (`id`),
INDEX `idx_name` (`name` ASC),
INDEX `fk_hotel_alias_hotel_idx` (`hotel_id` ASC),
CONSTRAINT `fk_hotel_alias_hotel`
FOREIGN KEY (`hotel_id`)
REFERENCES `my_app`.`hotel` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
CREATE TABLE IF NOT EXISTS `my_app`.`destination` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NOT NULL,
PRIMARY KEY (`id`),
INDEX `idx_name` (`name` ASC))
ENGINE = InnoDB
CREATE TABLE IF NOT EXISTS `my_app`.`place` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NOT NULL,
`destination_id` INT NOT NULL,
PRIMARY KEY (`id`),
INDEX `idx_name` (`name` ASC),
INDEX `fk_place_destination1_idx` (`destination_id` ASC),
CONSTRAINT `fk_place_destination1`
FOREIGN KEY (`destination_id`)
REFERENCES `my_app`.`destination` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
I want to create a view to populate a jquery autocomplete so I made the next query
SELECT name, 'hotel' AS type, (SELECT id FROM destination WHERE hotel.destination_id = destination.id) AS destination_id FROM hotel
UNION
SELECT name, 'place' AS type, (SELECT id FROM destination WHERE place.destination_id = destination.id) AS destination_id FROM place
UNION
SELECT name, 'alias' AS type, (SELECT destination.id FROM destination,hotel WHERE hotel_alias.hotel_id = hotel.id AND hotel.destination_id = destination.id) AS destination_id FROM hotel_alias
which returns the following results
|name |type |destination_id
---------------------------------------------------
|hotel casa maya |hotel |1
|sandos caracol |hotel |2
|cabañas tulum |hotel |3
|sandos luxury |hotel |1
|ocean spa |hotel |1
|sandos playacar |hotel |2
|walmart |place |1
|walmart |place |2
|centro |place |3
|campo de golf pok-ta-pok |place |1
|sandos beach scape |alias |2
|sunset spa |alias |1
The results are correct, but I wonder if Im using "subqueries" and "union" correctly or if is there a better way to generate the same result by optimizing the query?
Gracias!