现在有两个表,其中A表中有几个字段,其中一个是id,表B中有几个字段,其中一个是id,其他还有一个字段hid。表B只是表A的一个子集(即表B中和表A中id相同的记录可能有也可能没有),现在我想获得一个新表,包括表A的几个字段和表B的hid字段,如果表B中没有的记录,相应的hid字段置为null。举例:
表A:id f1 f2 f3 f4 f5
1 1 1 1 1 1
2 2 2 2 2 2
3 3 3 3 3 3表B:id hid f0
1 9 0想得到的结果:id f1 f2 f3 f4 hid
1 1 1 1 1 9
2 2 2 2 2 null
3 3 3 3 3 null
表A:id f1 f2 f3 f4 f5
1 1 1 1 1 1
2 2 2 2 2 2
3 3 3 3 3 3表B:id hid f0
1 9 0想得到的结果:id f1 f2 f3 f4 hid
1 1 1 1 1 9
2 2 2 2 2 null
3 3 3 3 3 null
declare @A table(id int,f1 int,f2 int,f3 int,f4 int,f5 int)
insert @A
select 1,1,1,1,1,1 union all
select 2,2,2,2,2,2 union all
select 3,3,3,3,3,3
--原始数据:@B
declare @B table(id int,hid int,f0 int)
insert @B
select 1,9,0select a.*,b.hid from @A a left join @B b on a.id=b.id/*
id f1 f2 f3 f4 f5 hid
----------- ----------- ----------- ----------- ----------- ----------- -----------
1 1 1 1 1 1 9
2 2 2 2 2 2 NULL
3 3 3 3 3 3 NULL
*/
select a.*,b.hid from 表A a left join 表B b on a.id=b.id