sql连接查询问题

来源:百度知道 编辑:UC知道 时间:2024/05/27 13:24:55
有两个表
a表
id val1
1 a
3 b
b表
id val2
1 a
2 b
4 d
连接查询
得到这样的结果
id val1 val2
1 a a
2 null b
3 c null
4 null d

select t0*,t1.val2 from a t0 left jion b t1 on a.id=b.id
union
select t0*,t1.val2 from b t0 left jion a t1 on a.id=b.id

大概就是这样,你自己在看看左连接

select a.id,val1,val2
from
(select a.id,val1,val2 from a left join b on a.id=b.id
union
select a.id,val1,val2 from b left join a on a.id=b.id)
order by a.id

select id,val1,null from a
union
select id,null,val2 from b

--> -->

if not object_id('Tempdb..#a') is null
drop table #a
Go
Create table #a([id] int,[val1] nvarchar(1))
Insert #a
select 1,N'a' union all
select 3,N'b'
Go
--> -->

if not object_id('Tempdb..#b') is null
drop table #b
Go
Create table #b([id] int,[val2] nvarchar(1))
Insert #b
select 1,N'a' union all
select 2,N'b' union all
select 4,N'd'
Go
select ID,max(val1)as val1,max(val2)