我有一张这样的表:
id | version | name
1 1 name1 v1
1 2 name1 v2
1 3 name1 v3
1 4 name1 v4
2 1 name2 v1
2 2 name2 v2
2 3 name2 v3
我正在尝试使用此查询获取表中每个id的最大版本:
SELECT a.id, MAX(a.version) AS version, b.name
FROM table1 a
INNER JOIN (
SELECT * FROM table1
) b
ON a.id = b.id AND a.version = b.version
GROUP BY a.id
但我得到了这些结果:
id | version | name
1 4 name1 v1
2 3 name2 v1
当我得到这个时:
id | version | name
1 4 name1 v4
2 3 name2 v3
任何帮助都将受到高度赞赏,提前感谢
编辑:
我刚刚意识到在select语句中添加max(b.name)可以解决问题
无论如何,感谢@bluefeet,@ user2001117,@ rs。和@Bram Gerritsen。您的所有查询都像魅力=)
答案 0 :(得分:1)
这样做
SELECT a.id, a.version, a.name
FROM table1 a
INNER JOIN (
SELECT id, max(version) version FROM table1
GROUP BY id
) b
ON a.id = b.id AND a.version = b.version
答案 1 :(得分:1)
试试这个:
SELECT a.id, a.version, a.name
FROM table1 a
INNER JOIN (
SELECT id, max(version) version FROM table1
GROUP BY id
) b
ON a.id = b.id AND a.version = b.version
答案 2 :(得分:1)
您需要更改查询以在子查询中使用聚合。获得子查询中每个max(version)
的{{1}}后,您将在这两个值上将其加回到您的表中,它将返回正确的结果:
id
答案 3 :(得分:1)
SELECT a.id, a.version, a.name
FROM table1 a
INNER JOIN (
SELECT id, max(version) version FROM table1
GROUP BY id
) b
USING(id, version)