Select the correct database row to achieve grouped results
P粉270842688
P粉270842688 2024-04-05 10:37:31
0
1
554

I want to select the best score for each user for a specific game.

My current query selects the score, date_saved, and username of the result for skill_game with id 1.

SELECT MAX(score) as score, date_saved, users.username FROM results
INNER JOIN users_results ON results.id = users_results.result_id
INNER JOIN users ON users_results.user_id = users.id
WHERE skill_game_id = 1
GROUP BY user_id
ORDER BY score  DESC

The results are as follows:

| score | username | date_saved |
---------------------------------
|    73 |     Mark | 2021-09-06 |
|    51 |     John | 2018-08-16 |
|    46 |     Ryan | 2020-02-20 |
|    43 |    Chris | 2019-08-27 |
|    40 |   Steven | 2020-07-04 |

Currently, date_saved is not always correct, as Mark's 73-point result was actually saved on 2021-11-03. The following are Mark’s results:

| score | username | date_saved |
---------------------------------
|    73 |     Mark | 2021-11-03 |
|    35 |     Mark | 2021-10-29 |
|    24 |     Mark | 2021-09-06 |

The GROUP BY statement selects the first row in the group, and MAX(score) selects the highest score in the group. I want to be able to select the highest score and select the corresponding date, but I'm not sure how to achieve this in MySQL.

P粉270842688
P粉270842688

reply all(1)
P粉964682904

You can also do it by selecting the largest date_saved

SELECT MAX(score) as score, MAX(date_saved), users.username FROM results
INNER JOIN users_results ON results.id = users_results.result_id
INNER JOIN users ON users_results.user_id = users.id
WHERE skill_game_id = 1
GROUP BY user_id
ORDER BY score  DESC
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template