表A
typeID NAME
1 AAA
2 BBB
3 CCC
4 DDD
表B
id title typeID
1 中国 1
2 美国 3
3 英国 3
4 日本 1我想取出表A的记录 然后再取表B中对应的类型的最大ID的那条记录 应该怎么写? 比如最后的结果是
1 AAA 4 日本 1
2 BBB null
3 CCC 3 英国 3
4 DDD null
typeID NAME
1 AAA
2 BBB
3 CCC
4 DDD
表B
id title typeID
1 中国 1
2 美国 3
3 英国 3
4 日本 1我想取出表A的记录 然后再取表B中对应的类型的最大ID的那条记录 应该怎么写? 比如最后的结果是
1 AAA 4 日本 1
2 BBB null
3 CCC 3 英国 3
4 DDD null
left join
B on A.typeID=B.typeiD and B.id in (
select max(id) as id from B group by typeID)
union all select 2, 'BBB'
union all select 3, 'CCC'
union all select 4, 'DDD'create table B(id int, title nvarchar(10), typeID int)
insert B select 1, '中国', 1
union all select 2, '美国', 3
union all select 3, '英国', 3
union all select 4, '日本', 1
select * from A
left join
B on A.typeID=B.typeiD and B.id in (
select max(id) as id from B group by typeID)--resulttypeID name id title typeID
----------- ---- ----------- ---------- -----------
1 AAA 4 日本 1
2 BBB NULL NULL NULL
3 CCC 3 英国 3
4 DDD NULL NULL NULL(4 row(s) affected)
insert ta select 1 , 'AAA'
union all select 2 , 'BBB'
union all select 3 , 'CCC'
union all select 4 , 'DDD'
create table tb(id int, title varchar(10), typeID int)
insert tb select 1 , '中国' ,1
union all select 2 , '美国' ,3
union all select 3 , '英国' ,3
union all select 4 , '日本' ,1select a.*,b.* from ta a
left join
(select b.* from tb b
inner join
(select max(id) mi from tb group by typeid) c
on mi=id
) b
on b.typeid=a.typeid
drop table ta,tb
left join tb b
on b.typeid=a.typeid
where not exists(select 1 from tb where typeid=b.typeid and id>b.id)