我有一个数据库表thanks_entry
带列
- entryid
- varname
- userid
- contenttype
- contentid
- dateline
- receiveduserid
此表存储用户/用户给予/收到的喜欢/感谢的数据
我想得到每月最喜欢/感谢用户的统计数据
查询:
SELECT receiveduserid,COUNT(receiveduserid) AS receivedthanks
FROM thanks_entry
WHERE varname ='likes' AND dateline > 1420070400
AND dateline <1422748800
GROUP BY userid ORDER BY COUNT(receiveduserid) DESC LIMIT 20
此查询应返回按用户ID分组的结果。。但看看结果我发现
- receiveduserid|receivedthanks
- 185883|190
- 43455|100
- 163068|85
- 2|66
- 186270|49
- 189468|34
- 105597|22
- 2|17
- 186270|17
- 163068|16
- 117147|15
- 186270|15
- 186270|14
- 186643|13
- 2|12
- 189170|12
- 118500|8
- 2|8
- 105597|8
- 2|7
正如你在这里注意到的,尽管我
grouped by receiveduserid
。。receiveduserid 2
未分组并在结果中多次出现。。我做错什么了?
最佳答案
试试这个:你可能想跟着这个
SELECT receiveduserid,COUNT(receiveduserid) AS receivedthanks
FROM thanks_entry
WHERE varname ='likes' AND dateline > 1420070400
AND dateline <1422748800
GROUP BY receiveduserid ORDER BY receivedthanks DESC LIMIT 20
您想按多个列分组,然后使用
,
(逗号)就像GROUP BY receiveduserid, another_column
第一列优先。。。