I have a users table with the following data:
+----+------------+--------------+--------------+--------------+ | 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 | +----+------------+--------------+--------------+--------------+
I want to be able to show overall ranks, where the ranking is defined as the overall highest score rather than a ranking per game. So in the example above, what query would I use to display this result:
+----+------------+-------+----------------+ | 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 | +----+------------+-------+----------------+
The following query answers your question:
A bit crude due to repetitiveness of the GREATEST(…) calculation. You may wish to put that in a subquery.
At any case, make note that this query will not utilize any index on the table since the ORDER BY uses a function over columns — that negates usage of a key in MySQL.