MySQL的子查询使用联合VS左联接?

时间:2019-06-14 05:37:29

标签: mysql

我正在尝试优化我的sql子查询。

这是我使用sudo ng serve并选择子查询中的字段的sql查询的旧版本:

UNION

经过一番研究后,这是我想出的新方法,它使用了据说更好的SELECT * FROM ( SELECT t7.*, '7' AS priority FROM ( SELECT `mytable`.`id`, `mytable`.`title`, `mytable`.`cover_photo`, `mytable`.`city_id`, `mytable`.`city_name`, `cities`.`name` AS `master_city_name`, `mytable`.`state_id`, `mytable`.`state_name`, `states`.`name` AS `master_state_name`, `countries`.`id` AS `country_id`, `countries`.`name` AS `country_name` FROM `mytable` LEFT JOIN `cities` ON `cities`.`id` = `mytable`.`city_id` LEFT JOIN `states` ON `states`.`id` = `mytable`.`state_id` LEFT JOIN `countries` ON `countries`.`id` = `mytable`.`country_id` JOIN `users` ON `users`.`id` = `mytable`.`user_id` WHERE `mytable`.`status` = 'published' AND `mytable`.`city_id` = '161' ) AS t7 UNION SELECT t8.*, '8' AS priority FROM ( SELECT `mytable`.`id`, `mytable`.`title`, `mytable`.`cover_photo`, `mytable`.`city_id`, `mytable`.`city_name`, `cities`.`name` AS `master_city_name`, `mytable`.`state_id`, `mytable`.`state_name`, `states`.`name` AS `master_state_name`, `countries`.`id` AS `country_id`, `countries`.`name` AS `country_name` FROM `mytable` LEFT JOIN `cities` ON `cities`.`id` = `mytable`.`city_id` LEFT JOIN `states` ON `states`.`id` = `mytable`.`state_id` LEFT JOIN `countries` ON `countries`.`id` = `mytable`.`country_id` JOIN `users` ON `users`.`id` = `mytable`.`user_id` WHERE `mytable`.`status` = 'published' AND `mytable`.`state_id` = '12' ) AS t8 UNION SELECT t9.*, '9' AS priority FROM ( SELECT `mytable`.`id`, `mytable`.`title`, `mytable`.`cover_photo`, `mytable`.`city_id`, `mytable`.`city_name`, `cities`.`name` AS `master_city_name`, `mytable`.`state_id`, `mytable`.`state_name`, `states`.`name` AS `master_state_name`, `countries`.`id` AS `country_id`, `countries`.`name` AS `country_name` FROM `mytable` LEFT JOIN `cities` ON `cities`.`id` = `mytable`.`city_id` LEFT JOIN `states` ON `states`.`id` = `mytable`.`state_id` LEFT JOIN `countries` ON `countries`.`id` = `mytable`.`country_id` JOIN `users` ON `users`.`id` = `mytable`.`user_id` WHERE `mytable`.`status` = 'published' AND `mytable`.`country_id` = '64' ) AS t9 ) AS t ORDER BY `t`.`priority`, RAND() LIMIT 25 并在主查询中选择了字段:

LEFT JOIN

从性能角度来看,哪一个更可取?

0 个答案:

没有答案