-1

我有一张这样的桌子:

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。您的所有查询都像魅力一样工作=)

4

4 回答 4

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)
于 2013-02-15T15:24:39.833 回答
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
于 2013-02-15T15:19:41.753 回答
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
于 2013-02-15T15:20:25.230 回答
1

您需要更改查询以在子查询中使用聚合。一旦在子查询中获得max(version)for each id,您将在这两个值上将其加入到您的表中,它将返回正确的结果:

select a.id,
  a.version,
  a.name
from table1 a
inner join
(
  select max(version) MaxVersion, id
  from table1 
  group by id
) b
  on a.id = b.id
  and a.version = b.maxversion

请参阅带有演示的 SQL Fiddle

于 2013-02-15T15:20:26.273 回答