我正在创建一个活动提要,显示我的用户活动,该活动仅限于最后 5 行。
SELECT * FROM activity ORDER BY date desc LIMIT 5
问题是我不希望活动提要在任何时候都被同一个用户弄乱,所以我想检索 user_id 彼此不同的最后 5 个结果。
我怎么能这样做呢?
这应该有效:
SELECT user_id, MAX(date) FROM activity GROUP BY user_id ORDER BY date DESC LIMIT 5
如果每个用户都没有多个max(date)
,则可以使用:
SELECT *
FROM activity
WHERE (user_id, `date`) IN (
SELECT * FROM (
SELECT user_id, max(`date`)
FROM activity
GROUP BY user_id
ORDER BY max(`date`) DESC
LIMIT 5) s
)
ORDER BY `date` DESC
请在此处查看小提琴。
我想使用这样的查询会很容易
SELECT DISTINCT activity.user_id,activity.* order by date DESC limit 5
Mysql Distinct 参考:http ://dev.mysql.com/doc/refman/5.1/en/distinct-optimization.html
它可以帮助你。
SELECT * FROM activity GROUP BY user ORDER BY date DESC LIMIT 5
试试这个查询,SELECT DISTINCT * FROM activity ORDER BY date desc LIMIT 5