【发布时间】:2012-09-25 08:52:48
【问题描述】:
我有两张桌子 - table1 和 table2。
两个表具有相同的列。
我想提取记录差异-意思是提取table1中的记录而不是table2中的记录,并提取table2中的记录而不是table1中的记录。
如何在 Oracle Sys 中使用 SQL 来做到这一点?
【问题讨论】:
标签: sql oracle set-operations
我有两张桌子 - table1 和 table2。
两个表具有相同的列。
我想提取记录差异-意思是提取table1中的记录而不是table2中的记录,并提取table2中的记录而不是table1中的记录。
如何在 Oracle Sys 中使用 SQL 来做到这一点?
【问题讨论】:
标签: sql oracle set-operations
要获得一个结果集中两个表的所有差异,您可以使用
select columnlist
from tableA
minus
select columnlist
from tableB
union all
select columnlist
from tableB
minus
select columnlist
from tableA
【讨论】:
minus 而不是 except
MINUS 获取一个 SELECT 语句的结果集,并删除 第二个 SELECT 语句也返回的那些行。
此查询将返回 table1 中的所有行,而不是 table2 中的所有行:
SELECT * FROM table1
MINUS
SELECT * FROM table2;
【讨论】:
select * from table1 where pk_col not in(select pk_col from table2)
select * from table2 where pk_col not in(select pk_col from table1)
【讨论】:
select t1.column1,t1.column2 from table1 t1 except select t2.column1,t2.column2 from table 2 t2 UNION all select t2.column1,t2.column2 from table 2 t2 except select t1.column1,t1.column2 from table1 t1
【讨论】:
select t1.Id,t1.name,t2.Id,t2.name from table1 t1 ,table2 t2 where t1.Id and t1.Name not in(select * from table2) and t2.Id,t2.name not in (select * from table 2)
【讨论】:
RomanKonz 的解决方案,附有哪些表实际包含行的附加信息(我通常使用 WITH 来简化实际的 UNION ALL / MINUS 部分):
with
v_a as (
select *
from tableA),
v_b as (
select *
from tableB)
select * from
(
(select 'A only' src, v.* from v_a v
minus
select 'A only' src, v.* from v_b v
)
union all
(select 'B only' src, v.* from v_b v
minus
select 'B only' src, v.* from v_b v
)
) order by primarykeycolumn, src
【讨论】: