我想从左表中获取所有值(忽略右表中具有相同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 |
----------------------
有没有简单的方法可以做到这一点?
谢谢。
答案 0 :(得分:5)
您可以使用union all
和not 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 Join
和Coalesce
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)