我想知道是否有人可以提供帮助。
我需要编写一个获取最后3个“创建”记录的查询,但是它们的UID必须是唯一的,例如,我的mysql字段看起来像这样
uid created
19 2012-02-01 01:08:43
18 2012-02-31 17:07:21
19 2012-02-31 16:07:20
20 2012-02-31 13:03:00
好的,所以我想要创建最后3个uid ...但是它们必须是唯一的uid,所以同样的uid不能出现两次。
干杯
答案 0 :(得分:0)
这应该这样做
SELECT * FROM ( SELECT * FROM tablename ORDER BY uid, created DESC ) ordered GROUP BY uid
答案 1 :(得分:0)
您可以使用此查询选择最后3个ID:
SELECT * FROM ( SELECT * FROM table ORDER BY uid, created DESC ) AS selected GROUP BY uid LIMIT 3
逻辑是:uid字段按降序排列表,限制为3个字段。
答案 2 :(得分:0)
SELECT *
FROM table
ORDER BY created DESC
GROUP BY uid LIMIT 0,3
答案 3 :(得分:0)
使用Distinct和Group by获取您之后的内容:
SELECT DISTINCT * FROM table GROUP BY uid;
这将为您提供所有独特的UID。 然后在那里添加你的ORDER BY以确保你获取最后的记录。
答案 4 :(得分:0)
SELECT uid
, MAX(created) AS max_created
FROM tableX
GROUP BY uid
ORDER BY max_created DESC
LIMIT 3