当前位置:首页> 编程笔记> MySql
关键字
文章内容
Mysql中Group by子句结合count使用的效率问题
 
 
修改时间:[2012/08/01 08:29]    阅读次数:[1581]    发表者:[沩筱]
 

articles
--------------
ID   标题   发布人     状态     是否推精
id     title   postby   status   isgood

要求取出发表文章最多的用户(优先按精华文章排)。

当然下面两种方法都不是最好方法,最好是将用户发表数量直接记录到用户表中去,但是有些时候数据库和程序已经设计好,要改动比较麻烦,那只有用以下方法了。

方法一
select postby,(select count(*) from articles where status=1 and postby=ar.postby) as art_num,(select count(*) from articles where status=1 and isgood=1 and postby=ar.postby) as goodart_num,title from articles as ar group by postby order by goodart_num desc,art_num desc limit 10

此方法中,group by子句在扫描表的时候,每一篇文章的都去执行了两次count,因此效率极低

方法二
select postby,sum(case when status=1 then 1 else 0 end) as art_num,sum(case when status=1 and isgood=1 then 1 else 0 end) as goodart_num,title from articles group by postby order by goodart_num desc,art_num desc limit 10

此方法,总共只需要执行一次表扫描,并且没有每次都count一下,而是用sum求一个总和,大大了减少了查询时间。效率会提高几百甚至几千倍

换一个思路有时候会豁然开朗!