我如何为每个唯一 ID 获取具有 MAX(field) 的行的数据

How do i get data of a row with MAX(field) for each unique id

我有一个tableGameData

--id(primary)--playTime--gameId--score--userId(foreign)
   1             100       1      50     asd
   2             150       1      100    asd
   3             200       2      150    asd
   4             200       2      40     qwe
   5             100       1      60     qwe
   6             90        1      30     qwe
   7             180       2      10     qwe

给定 userId 我想为每个唯一的 gameId.

获取具有 最高播放时间的行

例如,如果用户 ID = "asd",查询应该 return:

[
{playTime:150,gameId:1,score:100},{playTime:200,gameId:2,score:150}


]

if userId is = "qwe" query should return:

   [
    {playTime:100,gameId:1,score:60},{playTime:200,gameId:2,score:40}


    ]

这是我尝试过的方法,但它确实给出了预期的结果:

 "SELECT GameData.score,MAX(GameData.playTime) as playTime,GameData.gameId FROM GameDataWHERE GameData.userId=? GROUP BY GameData.gameId"

您可以尝试以下查询 -

SELECT GD.playTime, GD.gameId, GD.score
FROM (SELECT MAX(playTime) playTime, gameId
      FROM GameData
      WHERE userId = 'qwe'   -- Or asd
      GROUP BY gameId) M_ID
JOIN GameData GD ON M_ID.playTime = GD.playTime
                 AND M_ID.gameId = GD.gameId