1

我有一张桌子,usersposts希望获得用户在不同日期范围内的帖子计数。

users: id, username
1, bob
2, sam

posts: id, user_id, created (datetime)
1, 1, 2012-12-01 00:00:00
2, 1, 2012-12-30 00:01:00
3, 1, 2012-12-30 01:00:00
4, 2, 2012-12-12 00:00:00
5, 2, 2012-12-30 01:00:00

我想计算最后一个月hour的帖子。day这可以在一个查询中完成吗?

假设查询运行的日期是2012-12-30 01:30:00我想要如下内容:

User.id | hour | day | month
1       | 1    | 2   | 3
2       | 1    | 1   | 2

我尝试过类似以下的操作,但数字是错误的。

SELECT 
    User.id, 
    COUNT(Hour.id) as hour, 
    COUNT(Day.id) as day, 
    COUNT(Month.id) as month
FROM user as User
LEFT JOIN posts as Hour ON 
    (posts.user_id = user.id AND posts.created >= '2012-12-30 00:30:00')
LEFT JOIN posts as Day ON 
    (posts.user_id = user.id AND posts.created >= '2012-12-29 01:30:00')
LEFT JOIN posts as Month ON 
    (posts.user_id = user.id AND posts.created >= '2012-11-30 01:30:00')

我最终得到了奇怪的数字,例如

User.id | hour | day | month
1       | 12   | 12  | 12
2       | -    | 2   | 2
4

1 回答 1

3

你可以使用这个:

select
  username,
  user_id,
  sum(created>=date_sub('2012-12-30 01:30:00', INTERVAL 1 HOUR)) hour,
  sum(created>=date_sub('2012-12-30 01:30:00', INTERVAL 1 DAY)) day,
  count(*) month
from users inner join posts on users.id=posts.user_id
where created>=date_sub('2012-12-30 01:30:00', INTERVAL 1 MONTH)
group by user_id

(然后您可以用 替换特定的日期'2012-12-30 01:30:00'时间now()

于 2012-12-30T16:59:26.460 回答