Mysql中Group by子句结合count使用的效率问题

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求一个总和,大大了减少了查询时间。效率会提高几百甚至几千倍

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

 

解决了我的问题,转载过来啦先。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值