当前位置: 代码迷 >> Sql Server >> 两表查询的有关问题
  详细解决方案

两表查询的有关问题

热度:51   发布时间:2016-04-24 09:53:35.0
请教大家两表查询的问题?
有两个表:
表A
用户名 帐号 数值
A1          60    100 
A1          35    120
A1          48    110
......

表B 
用户名  帐号 数值
A1          60    90
A1          35    110
A1          48    100
A1          23     90
A1          54     130
......

想得到以下的结果:
用户名  帐号 数值
A1          60    100
A1          35    120
A1          48    110
A1          23     90
A1          54     130

就是在结果中两表中同一用户名的数据合并在一起,表A中有的数据就用表A的,表A中没有的数据就用表B的,这个SQL语句要怎么写呢?先谢谢大家了!!!


------解决思路----------------------
select 用户名, 帐号, 数值 from 表A
union all
select 用户名, 帐号, 数值 from 表B as b where not exists (select 用户名, 帐号, 数值 from 表A where 用户名=b.用户名 and 帐号=b.帐号)
------解决思路----------------------
select * from A
union 
select * from B
where not exists (
  select 1 from a
 where 用户名 = b.用户名 and 帐号 = b.帐号
)
------解决思路----------------------
select 
用户名 = isnull(a.用户名,b.用户名)
, 帐号 = isnull(a. 帐号,b. 帐号)
, 数值 = isnull(a.数值,b.数值)
from a full join b
on a.用户名= b,用户名 and a. 帐号= b. 帐号 

------解决思路----------------------
select * from a
union all
select * from b where  帐号 not in (select 帐号  from a)
  相关解决方案