我有一张桌子,users
并posts
希望获得用户在不同日期范围内的帖子计数。
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