这是2个表 -
Table A
id | col1 | col2
----------------
1 | val1 | val2
2 | val3 | val4
Table B
id | version | col3 | col4
--------------------------
1 | 1 | val5 | val6
1 | 2 | val7 | val8
我想获取A.col1,A.col2,B.col3,B.col4的值,其中A.id = B.id和B.version是最大版本。因此,我想要一个像 -
这样的结果集id | version | col1 | col2 | col3 | col4
----------------------------------------
1 | 2 | val1 | val2 | val7 | val8
可以使用哪种SQL查询来实现此结果?
谢谢!
答案 0 :(得分:2)
select a.id, b2.version, a.col1, a.col2, b.col3, b.col4
from a
join b on a.id=b.id
join (select id, max(version) version from b group by id) b2 on b2.id=b.id and b2.version=b.version
答案 1 :(得分:1)
与之前的答案类似,但实际上您只能使用一个连接而不是两个:
准备测试数据:
Select * INTO #TableA
from (
Select 1 as ID , 'val1' as col1, 'val2' as col2
UNION Select 2, 'val3', 'val4'
) A
Select * INTO #TableB
from (
Select 1 as id, 1 as version, 'val5' as col3, 'val6' as col4
UNION Select 1, 2, 'val7', 'val8'
) B
获得结果:
Select A.col1, A.col2, B.col3, B.col4
from #TableA A
JOIN (
Select ID, max(version) as version, max(col3) as col3, max(col4) as col4 from #TableB Group By ID
) B ON A.ID = B.ID
答案 2 :(得分:0)
试试这个:
SELECT *
FROM A
INNER JOIN (
SELECT * FROM B
INNER JOIN (
SELECT ID, MAX(Version)
FROM B
GROUP BY ID
) XXX ON (B.ID = XXX.ID)
) YYY ON (A.ID = YYY.ID)
答案 3 :(得分:0)
在SQL Fiddle上试过这个:
select tableA.id, version, col1, col2, col3, col4 from tableA
join tableB on tableA.id = tableB.id
where version = (select max(version) from tableB where tableB.id = tableA.id);
这将为您提供一个结果集,其中包含表B中表A中每个id的最大版本和相应值。
答案 4 :(得分:0)
根据文档Group-wise Maximum of a Certain Column
,您可以将查询编写为
select a.*,
b.`col3`,
b.`col4`,
b.version
from a
join b on(a.id = b.id)
left join b b2 on(b.id = b2.id and b.version < b2.version)
where b2.id is null
Fiddle Demo