简体   繁体   English

mysql如何显示每个用户的最高分

[英]How to display the highest score of each user with mysql

Suppose I have a database with two tables.假设我有一个包含两个表的数据库。 A "user" table containing an ID, first name, and last name.包含 ID、名字和姓氏的“用户”表。 And a "game" table containing an ID, score, and a userID (the same ID from the user table).还有一个“游戏”表,其中包含一个 ID、分数和一个用户 ID(与用户表相同的 ID)。

-------------------------              ------------------------
ID | fName | lName                     ID | score | userID
-------------------------              ------------------------
1  |  Joe  | Smith                     1  |   20  |    2
2  |  Jane | Doe                       2  |   15  |    2
3  |  Sam  | Mills                     3  |   18  |    3
--------------------------          4  |   22  |    3

I want to get ONLY the highest score of each user that has played the game.我只想获得每个玩过游戏的用户的最高分。 I want to display something like this:我想显示这样的东西:

                      Jane |  Doe  | 20
                      Sam  | Mills | 22

Using mysql, how can I achieve this?使用 mysql,我该如何实现呢? Also do I need to take into account that there are no records for Joe Smith (userID = 1) in the "game" table?我还需要考虑到“游戏”表中没有 Joe Smith (userID = 1) 的记录吗?

Thank You to whoever can help!感谢任何可以提供帮助的人!

You can use aggregation and join :您可以使用聚合和join

select u.fname, u.lname, gu.max_score
from (select userid, max(score) as max_score
      from games g               
      group by userid
     ) gu join
     users u
     on u.id = gu.userid

For achieve this you can use aggregation function and left join:为此,您可以使用聚合 function 和左连接:

SELECT U.id, U.fname, U.lname,IFNULL(MAX(G.score),0) AS score FROM user AS U
LEFT JOIN game AS G ON G.userID = U.id
GROUP BY U.id, U.fname, U.lname

I have used left join so if game table don't have any user record so it would be returning 0.我使用了左连接,所以如果游戏表没有任何用户记录,那么它将返回 0。

This is DB FIDDLE link you can check same Qry there.这是DB FIDDLE链接,您可以在那里检查相同的 Qry。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM