SQL Query从左表获取所有值,从右表获取不常见的值

时间:2014-11-03 18:02:46

标签: sql sql-server

我想从左表中获取所有值(忽略右表中具有相同id的公共值)和右表中左表中不存在的所有值。

表1:

----------------------
|   id   |    value  |
----------------------
|   1    |    50     |
----------------------
|   2    |    150    |
----------------------
|   4    |    100    |
----------------------

表2:

----------------------
|   id   |    value  |
----------------------
|   1    |    300    |
----------------------
|   3    |    150    |
----------------------
|   4    |    250    |
----------------------

预期结果:

----------------------
|   id   |    value  |
----------------------
|   1    |    50     |
----------------------
|   2    |    150    |
----------------------
|   3    |    150    |
----------------------
|   4    |    100    |
----------------------

有没有简单的方法可以做到这一点?

谢谢。

4 个答案:

答案 0 :(得分:5)

您可以使用union allnot exists子句:

select id, value
from table1 t1
union all
select id, value
from table2 t2
where not exists (select 1 from table1 t1 where t1.id = t2.id);

答案 1 :(得分:1)

select * from 
(
select * from tab1
except
select * from tab2
UNION ALL
select id, value
from tab2 t2
where not exists (select 1 from tab1 t1 where t1.id = t2.id))d
order by d.id ;

<强>输出

id  value
1   50
2   150
3   150
4   100

答案 2 :(得分:0)

您也可以使用Full JoinCoalesce

执行此操作
Select      Coalesce(L.Id, R.Id) Id,
            Coalesce(L.Value, R.Value) Value
From        Table1  L
Full Join   Table2  R On L.Id = R.Id
Order By    Id

答案 3 :(得分:0)

select distinct *
from
(select id, value
from table1 t1
union all
select id, value
from table2 t2)