码迷,mamicode.com
首页 > 其他好文 > 详细

join on 和group

时间:2019-04-01 17:02:06      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:基础上   hits   而不是   color   select   from   image   nbsp   处理   

技术图片                    技术图片

左边的表是article文章表,右边的是comment文章回复表。

今天mysql查询的时候,遇到了有趣的事,任务是查询数据库需要得到以下格式的文章标题列表,并按照回复数量排序,回复最高的排在最前面。

“文章id   文章标题       点击量   回复数量”,

没有回复的,默认回复数量为0.  最开始想到的答案是  select a.id,a.title,a.hits,count(c.comment_id) as total from article as a left join comment as c on a.id=c.art_id group by c.art_id order by total desc;  但是查询出来的结果却是明显不符合题意,少了一行数据;

技术图片  

正确答案是   select a.id,a.title,a.hits,count(c.comment_id) as total from article as a left join comment as c on a.id=c.art_id group by a.id order by total desc; 

技术图片

还有一种查询方法(但是结果有null,不符合题意):select a.id,a.title,c.num from article as a left join (select art_id, count(comment_id) as num from comment group by art_id) as c on a.id = c.art_id order by c.num desc;

技术图片

他们的区别是什么?为什么会是这种结果?简单分析一下:先看这条语句    select a.id,a.title,a.hits from article as a left join comment as c on a.id=c.art_id;  

技术图片

根据结果来看就会明白join on 查询,会把满足a.id=c.art_id的数据每一条都查询出来,不论结果是否会重复(只要在表里的数据满足条件)。在这条语句基础上加count看看会发生什么,select a.id,a.title,a.hits,count(c.comment_id) as total from article as a left join comment as c on a.id=c.art_id;

技术图片

只显示一条数据了,因为没有任何的条件限制,所以count是在查询的所有结果中计算回复数量。到这里可以回头看第一次查询语句,他是按照c.art_id来分组,然后count在分组的基础上计算每个分组的回复数量,而文章ID为2和4的没有对应的分组,所以count把他们按照一个组来处理了,就得到了如图所示的结果。而正确答案是按照a.id来分组的,也就是文章ID为2和4的有各自的分组,就得到了正确的结果。而第三种会有值为null的情况为什么?因为他是嵌套查询,select art_id, count(comment_id) as num from comment group by art_id;这条子句查询的结果是 

技术图片

也就是说相当于join on是查询文章表和这张表,而不是查询文章表和文章回复表了,也就是这两张表的left join on 正常查询的出来的结果。

join on 和group

标签:基础上   hits   而不是   color   select   from   image   nbsp   处理   

原文地址:https://www.cnblogs.com/bneglect/p/10637247.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!