我有一张像这样的签到记录表:
userID checkin_date
1 '2014-01-28 08:00:00'
1 '2014-01-27 09:10:00'
1 '2014-01-26 12:24:00'
2 '2014-01-26 08:17:00'
3 '2014-01-26 09:33:00'
2 '2014-01-28 10:28:00'
.. .........
我希望用一个请求对自特定日期以来签入最多的十个用户进行排序(通过nb visite DESC订购)(这很简单),但对于每个用户,我还想知道他们上次登记的日期。< / p>
我这样做:
SELECT
userID,
count(*) as nbVisit,
checkin_date
FROM(
SELECT
userID,
checkin_date
FROM checkin_table
WHERE checkin_date > '2014-01-25'
ORDER BY checkin_date DESC )as sub
GROUP BY userID
ORDER BY nbVisit DESC
LIMIT 10
这是最好的方法吗?它会随时工作吗?大量数据是否有效?
答案 0 :(得分:2)
您不需要子查询,只需使用max()
和count(*)
:
SELECT userID, max(checkin_date), count(*) as nbVisit,
FROM checkin_table
WHERE checkin_date > '2014-01-25'
GROUP BY userId
ORDER BY nbVisit desc
LIMIT 10 ;