我有一个包含以下数据的用户表:
+----+------------+--------------+--------------+--------------+ | id | name | points_game1 | points_game2 | points_game3 | +----+------------+--------------+--------------+--------------+ | 1 | player 1 | 10 | 0 | 5 | | 2 | player 2 | 0 | 25 | 0 | | 3 | player 3 | 30 | 3 | 0 | | 4 | player 4 | 0 | 0 | 20 | +----+------------+--------------+--------------+--------------+
我希望能够显示整体排名,其中排名被定义为总体最高分而不是每场比赛的排名。因此,在上面的示例中,我将使用什么查询来显示此结果:
+----+------------+-------+----------------+ | id | name | score | game | +----+------------+-------+----------------+ | 3 | player 3 | 30 | points_game1 | | 2 | player 2 | 25 | points_game2 | | 4 | player 4 | 20 | points_game3 | | 1 | player 1 | 10 | points_game1 | +----+------------+-------+----------------+
答案 0 :(得分:0)
以下查询回答了您的问题:
SELECT
id,
name,
GREATEST(points_game1, points_game2, points_game3) AS score,
CASE
WHEN points_game1 = GREATEST(points_game1, points_game2, points_game3) THEN 'points_game1'
WHEN points_game2 = GREATEST(points_game1, points_game2, points_game3) THEN 'points_game2'
WHEN points_game3 = GREATEST(points_game1, points_game2, points_game3) THEN 'points_game3'
END AS game
FROM
users
ORDER BY
3 DESC
由于GREATEST(...)计算的重复性而有点粗糙。您可能希望将其放在子查询中。
在任何情况下,请注意此查询不会使用表上的任何索引,因为ORDER BY使用了一个函数而不是列 - 这会消除MySQL中密钥的使用。