我有一个MySQL表“results”,其中包含以下字段:
id (PK, AI), user_id (FK), date, score, time
我希望能够查询此表,以便按照得分(降序)后跟时间(升序)对字段进行排序和返回。如下所示:
SELECT * FROM results ORDER BY score DESC, time ASC.
但是,在此排序之后,如果多个行具有相同的user_id
,我只想包含最高行。
我该怎么做?
答案 0 :(得分:1)
您可以使用not exists
:
SELECT *
FROM results r
WHERE NOT EXISTS (select 1 from results r2 where r2.user_id = r.user_id and r2.id > r.id)
ORDER BY score DESC;
这适用于results(user_id, id)
上的索引。
答案 1 :(得分:1)
我的建议:SELECT user_id, max(score), time FROM results GROUP BY user_id ORDER BY score DESC;
通过user_id
和max()
为Group By
选择ID和最高得分。然后按分数降序排列记录。
编辑:如果您需要用户得分的时间并且只有一个具有相同分数的条目,您可以使用子选择来获得这个时间:
SELECT user_id, max(score), (
SELECT max(time)
FROM results AS r2
WHERE r2.user_id = r1.user_id
AND r2.score = max(r1.score)
) AS time
FROM results AS r1
GROUP BY user_id
ORDER BY score DESC;
答案 2 :(得分:0)
我现在已经成功了。
SELECT user_id, score, time
FROM results T
WHERE T.score = (
SELECT MAX(T2.score)
FROM results T2
WHERE T2.user_id = T.user_id
)
ORDER BY score DESC, time ASC;