【问题标题】:sql - compare tablesql - 比较表
【发布时间】:2013-02-14 10:03:20
【问题描述】:

如何比较两个表并根据结果做出反应。例如。 我有 2 个表(精确结构):tableA(key, text) 和 tableB(key, text) 和一个结果表(key, field, case)。

if key is in tableA, but not in tableB --> case: insert
if key is in tableB, but not in tableA --> case: delete
if key is in tableA and in tableB, but the text is different -> update
if key is in tableA and in tableB, and the text is the same -> nothing

结果表如下:

key | text | case
------------------
1   |  t1  | update
2   |  t2  | delete
3   |  t3  | insert
4   |  t4  | nothing

是否可以只用一个查询来完成?

获取插入(删除反之亦然):

SELECT key FROM tableA
MINUS
SELECT key FROM tableB;

【问题讨论】:

    标签: sql oracle compare


    【解决方案1】:

    这会有帮助吗?

    SELECT NVL (a.key, b.key) AS "KEY",
           NVL (a.text, b.text) as "TEXT",
           CASE
              WHEN a.key IS NOT NULL AND b.key IS NULL THEN
                 'Insert'
              WHEN a.key IS NULL AND b.key IS NOT NULL THEN
                 'Delete'
              WHEN a.key IS NOT NULL AND b.key IS NOT NULL AND a.text != b.text THEN
                 'Update'
              WHEN a.key IS NOT NULL AND b.key IS NOT NULL AND a.text = b.text THEN
                 'Nothing'
           END
              "CASE"
      FROM tablea a FULL OUTER JOIN tableb b ON a.key = b.key;
    

    【讨论】:

    • 这是我一直在寻找的东西,它给了我正确的结果。但是,如果我必须比较更多的文本列。我必须全部添加它们还是有机会像“比较除键之外的所有内容”?
    • 除了将它们全部添加之外,我现在想不出任何办法。
    【解决方案2】:

    我认为你需要这样的东西:

      select 'IN Table1, NOT Table2', Key_column
        from user_tab_columns
       where table_name = 'Table1'
      MINUS
      select 'IN Table1, NOT Table2', Key_column
        from user_tab_columns
       where table_name = 'Table2'
      )
      UNION ALL
      (
      select 'IN Table2, NOT Table1', Key_column
        from user_tab_columns
       where table_name = 'Table2'
      MINUS
      select 'IN Table2, NOT Table1', Key_column
        from user_tab_columns
       where table_name = 'Table1'
      )
    

    您可以在链接中找到此概念的一些示例和变体:http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1004115105172

    祝你好运。

    【讨论】:

      猜你喜欢
      • 2016-11-23
      • 1970-01-01
      • 1970-01-01
      • 2018-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多