【问题标题】:Extract the different recored in two table提取两个表中的不同记录
【发布时间】:2012-09-25 08:52:48
【问题描述】:

我有两张桌子 - table1table2。 两个表具有相同的列。

我想提取记录差异-意思是提取table1中的记录而不是table2中的记录,并提取table2中的记录而不是table1中的记录。

如何在 Oracle Sys 中使用 SQL 来做到这一点?

【问题讨论】:

    标签: sql oracle set-operations


    【解决方案1】:

    要获得一个结果集中两个表的所有差异,您可以使用

    select columnlist
    from tableA
    minus
    select columnlist
    from tableB
    union all
    select columnlist
    from tableB
    minus
    select columnlist
    from tableA
    

    【讨论】:

    • Oracle 中是 minus 而不是 except
    【解决方案2】:

    MINUS 获取一个 SELECT 语句的结果集,并删除 第二个 SELECT 语句也返回的那些行。

    此查询将返回 table1 中的所有行,而不是 table2 中的所有行:

    SELECT * FROM table1
    MINUS
    SELECT * FROM table2;
    

    【讨论】:

      【解决方案3】:
      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)
      

      【讨论】:

      • 这是一个英文网站;请用英文写。
      【解决方案4】:
      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
      

      【讨论】:

        【解决方案5】:
        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)
        

        【讨论】:

          【解决方案6】:

          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 
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2013-01-09
            • 2016-12-01
            • 2015-02-15
            • 1970-01-01
            • 2019-03-22
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多