2013-02-14 83 views
0

如何比較兩個表並根據結果做出反應。例如。 我有2個表(確切結構):tableA(key,text)和tableB(key,text)和一個結果表(key,field,case)。sql - 比較表

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; 

回答

0

這會幫助嗎?

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; 
+0

這是我正在尋找並給我正確的結果。但是,如果我必須比較更多的文本列,那是什麼。我是否必須將它們全部添加或是否有機會比較「比較除鍵之外的所有內容」? – Marc 2013-02-14 10:28:09

+0

除了添加全部內容之外,我現在想不出任何方法。 – 2013-02-14 10:34:17

0

我想你需要的東西是這樣的:

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

祝你好運。