PHP SQL 按多行排序

PHP SQL order by multiple rows

我有一个名为 'scorelist' 的 table,结果如下:

ID   USER_ID   SCORE   SEASON
-----------------------------
1    1         35      3
2    1         45      2
3    2         80      3
4    2         85      1
5    3         65      2

我想制作一个分数列表,其中显示用户的分数,但只显示他们上个赛季的分数。 结果应该是:

ID   USER_ID   SCORE   SEASON
-----------------------------
3    2         80      3
5    3         65      2
1    1         35      2

我使用以下代码:

SELECT * FROM scorelist 
WHERE season = (
    SELECT season FROM scorelist ORDER BY season DESC LIMIT 1
) 
GROUP BY user_id 
ORDER BY score DESC;

但是后来我只得到了第3季的结果,所以很多用户没有显示。

我也试过:

SELECT * FROM scorelist group by user_id ORDER BY score DESC, season DESC

但这也行不通。
我希望你能帮助我。

子查询获取每个用户的最新一季。如果你加入,你会得到你想要的结果

SELECT s1.* 
FROM scorelist s1
JOIN 
(
   SELECT user_id, max(season) AS season
   FROM scorelist
   GROUP BY user_id
) s2 ON s1.user_id = s2.user_id AND s1.season = s2.season

从MySQL 8.0开始你可以使用window函数row_number来解决这个问题:

WITH ordered_scorelist AS (
    SELECT 
        scorelist.*, 
        row_number() over (partition by USER_ID order by SEASON DESC) rn 
    FROM scorelist
) SELECT 
    USER_ID, SCORE, SEASON 
FROM ordered_scorelist 
WHERE rn = 1 
ORDER BY SCORE DESC;

MySQL row_number test