如何通过 MYSQL 中的另一列选择具有 MAX(列值)、PARTITION 的行?
我的桌子是:
id | 家 | 日期时间 | 玩家 | 资源 |
---|---|---|---|---|
1 | 10 | 04/03/2009 | 约翰 | 399 |
2 | 11 | 04/03/2009 | 朱丽叶 | 244 |
5 | 12 | 04/03/2009 | 硼酸 | 555 |
3 | 10 | 03/03/2009 | 约翰 | 300 |
4 | 11 | 03/03/2009 | 朱丽叶 | 200 |
6 | 12 | 03/03/2009 | 硼酸 | 500 |
7 | 13 | 24/12/2008 | 硼酸 | 600 |
8 | 13 | 01/01/2009 | 硼酸 | 700 |
我需要选择每个不同的 home
保存 datetime
的最大值.
I need to select each distinct home
holding the maximum value of datetime
.
结果是:
id | 家 | 日期时间 | 玩家 | 资源 |
---|---|---|---|---|
1 | 10 | 04/03/2009 | 约翰 | 399 |
2 | 11 | 04/03/2009 | 朱丽叶 | 244 |
5 | 12 | 04/03/2009 | 硼酸 | 555 |
8 | 13 | 01/01/2009 | 硼酸 | 700 |
我试过了:
-- 1 ..by the MySQL manual:
SELECT DISTINCT
home,
id,
datetime AS dt,
player,
resource
FROM topten t1
WHERE datetime = (SELECT
MAX(t2.datetime)
FROM topten t2
GROUP BY home)
GROUP BY datetime
ORDER BY datetime DESC
不起作用.结果集有 130 行,尽管数据库有 187 行.结果包括 home
的一些重复项.
Doesn't work. Result-set has 130 rows although database holds 187.
Result includes some duplicates of home
.
-- 2 ..join
SELECT
s1.id,
s1.home,
s1.datetime,
s1.player,
s1.resource
FROM topten s1
JOIN (SELECT
id,
MAX(datetime) AS dt
FROM topten
GROUP BY id) AS s2
ON s1.id = s2.id
ORDER BY datetime
没有.提供所有记录.
-- 3 ..something exotic:
各种结果.
推荐答案
你们离得这么近!您需要做的就是选择家庭及其最大日期时间,然后在两个字段中加入 topten
表:
You are so close! All you need to do is select BOTH the home and its max date time, then join back to the topten
table on BOTH fields:
SELECT tt.*
FROM topten tt
INNER JOIN
(SELECT home, MAX(datetime) AS MaxDateTime
FROM topten
GROUP BY home) groupedtt
ON tt.home = groupedtt.home
AND tt.datetime = groupedtt.MaxDateTime
相关文章