用复杂谓词优化MySQL查询

时间:2013-05-31 04:29:47

标签: mysql

感谢您的帮助。我有一个名为posts的表,每个帖子都有一行。帖子有post_date(以unix时间戳格式)和author_id。

我试图获得按月和年份分组的一个月内发布5次或更多次的唯一作者的数量。

我现在按月和年份对唯一作者的查询(在该月内没有5个或更多帖子的过滤器):

select
    month(from_unixtime(p.post_date)) as month,
    year(from_unixtime(p.post_date)) as year,
    count(distinct p.author_id)
from posts p
group by month,year
order by year desc,month desc

你能否帮我添加一个过滤器,只计算那个月内有5个或更多帖子的作者?

更新

以下查询有效但速度极慢,即使仅在本月和年份添加谓词也是如此。有人可以想出更好的方法吗?

select
    month(from_unixtime(p.post_date)) as month,
    year(from_unixtime(p.post_date)) as  year,
    count(distinct p.author_id)
from posts p 
   where (
     select count(*) from posts p2 where p2.author_id=p.author_id
     and month(from_unixtime(p.post_date))=month(from_unixtime(p2.post_date))
     and year(from_unixtime(p.post_date))=year(from_unixtime(p2.post_date))
   )>=5
 group by month,year order by year desc,month desc

1 个答案:

答案 0 :(得分:1)

您可以使用计数> 5.它将解决问题

  select month(from_unixtime(p.post_date)) as month,
    year(from_unixtime(p.post_date)) as year,
    count( p.author_id) c from posts p 
    group by author , month,year having c >5 
    order by year desc,month desc