简体   繁体   中英

SQL Left Outer Join Affecting Sub Query Order

I have a query that contains a sub-query and many Left Outer Joins. Within my sub-query, I am ordering by records by the most recent blog_date and limiting the results by 10 records. This sub-query should dictate the order of the records with the other joins matching up additional information about that record, however, when I add in the LEFT OUTER JOIN it disregards the blog_date ordering. This has led me to believe that I am either missing a key element to persisting the ordering or that LEFT OUTER JOIN is not the right join to be using.

Here is my full query:

SELECT `b`.`blog_id`, `b`.`blog_date`,`b`.`title`, `u`.`user_id`, `u`.`first_name`, `c`.`category_name`, `d`.`discovery_source_name`, `bc`.`comment`, `bf`.`file`
FROM (SELECT * FROM `blog` ORDER BY `blog`.`blog_date` DESC limit 10) `b`
LEFT OUTER JOIN `user` `u` ON `b`.`user_id` = `u`.`user_id` AND `u`.`organization_id` = 1
LEFT OUTER JOIN `category` `c` ON `b`.`category_id` = `c`.`category_id`
LEFT OUTER JOIN `discovery_source` `d` ON `b`.`discovery_source_id` = `d`.`discovery_source_id`
LEFT OUTER JOIN `blog_comment` `bc` ON `b`.`blog_id` = `bc`.`blog_id`
LEFT OUTER JOIN `blog_file` `bf` ON `b`.`blog_id` = `bf`.`blog_id`
;

Here are the results when I just include the first join ( user ) the records are in the correct order (2017-02-21 most recent):

正确查询

However, when I add in the second left outer join (and remaining) it appears that the new order is in descending blog_date order, but then grouped by category_name .

错误的订单

Ordering the subquery has no effect on the order of your outer query. Put the ORDER BY at the end of the outer query.

SELECT `b`.`blog_id`, `b`.`blog_date`,`b`.`title`, `u`.`user_id`, `u`.`first_name`, `c`.`category_name`, `d`.`discovery_source_name`, `bc`.`comment`, `bf`.`file`
FROM (SELECT * FROM `blog` ORDER BY `blog`.`blog_date` DESC limit 10) `b`
LEFT OUTER JOIN `user` `u` ON `b`.`user_id` = `u`.`user_id` AND `u`.`organization_id` = 1
LEFT OUTER JOIN `category` `c` ON `b`.`category_id` = `c`.`category_id`
LEFT OUTER JOIN `discovery_source` `d` ON `b`.`discovery_source_id` = `d`.`discovery_source_id`
LEFT OUTER JOIN `blog_comment` `bc` ON `b`.`blog_id` = `bc`.`blog_id`
LEFT OUTER JOIN `blog_file` `bf` ON `b`.`blog_id` = `bf`.`blog_id`
ORDER BY `b`.`blog_date` DESC ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM