选择ID所有的行,但只选择最近出现重复的行

时间:2017-10-03 08:00:24

标签: mysql

我的数据库中有一个名为Stats的表:

| Game_ID | User_ID |  Rank | Creation_date |
---------------------------------------------
|       1 |       1 |    1  |    2017-04-03 |
|       1 |       2 |    2  |    2017-04-03 |
|       1 |       3 |    3  |    2017-04-03 |
|       1 |       1 |    4  |    2017-05-03 |

我目前使用以下查询来获取特定Game_ID的所有行:

"SELECT * FROM Stats WHERE Game_ID = 2 ORDER BY Rank ASC"

这将完全返回上面显示的内容,但我希望每个User_ID只返回一行(具有最新Creation_date的那一行),如下所示:

| Game_ID | User_ID |  Rank | Creation_date |
---------------------------------------------
|       1 |       2 |    2  |    2017-04-03 |
|       1 |       3 |    3  |    2017-04-03 |
|       1 |       1 |    4  |    2017-05-03 |

任何帮助将不胜感激!

修改

我尝试了上面的解决方案,并且我确定它是正确的。我不再获得User_ID的重复项了。但是,我没有获得最新的Creation_date。我错过了什么?

更新的查询:

SELECT a.Game_ID, a.User_ID, a.rank, a.Creation_date
            FROM stats a
            INNER JOIN (
                SELECT User_ID, MAX(Creation_date), Creation_date
                FROM stats
                WHERE Game_ID = 2
                GROUP BY User_ID
            ) b ON a.User_ID = b.User_ID AND a.Creation_date = b.Creation_date ORDER BY rank ASC;

返回:

| Game_ID | User_ID |  Rank | Creation_date |
---------------------------------------------
|       1 |       1 |    1  |    2017-04-03 |
|       1 |       2 |    2  |    2017-04-03 |
|       1 |       3 |    3  |    2017-04-03 |

换句话说,不是具有最新Creation_date for User_ID 1的行。

1 个答案:

答案 0 :(得分:-1)

试试这个 -

SELECT Game_ID, User_ID, MAX(Rank), Max(Creation_date)
FROM Stats 
WHERE Game_ID = 2
GROUP BY Game_ID, User_ID, Creation_date
ORDER BY Rank, Creation_date