2016-02-09 39 views
0

我有一個表的結構是這樣的:
表1包含爲col_a,col_b,col_c
表2包含爲col_a,col_b
從表1中刪除記錄,如果它是兩個字段值的組合不能在表中找到2

我希望能夠根據col_a和col_b值檢查表1中是否有任何記錄的col_a和col_b中的值與表2中的任何記錄不匹配。惠斯特還使用DBMS_OUTPUT記錄已刪除的內容。

因此,如果這是我的數據:

表1

-------------------------------------- 
     |col_a | col_b  | col_c | 
-------------------------------------- 
Row 1 |'apple' | 'ham'  | 'water' | 
------------------------------------ 
Row 2 |'pear' | 'chicken' | 'water' | 
------------------------------------- 
Row 3 | 'apple' | 'pork' | 'wine' | 
-------------------------------------- 

表2

---------------------------- 
     |col_a | col_b  | 
---------------------------- 
Row 1 |'apple' | 'ham'  | 
---------------------------- 
Row 2 |'pear' | 'pork' | 
---------------------------- 
Row 3 | 'orange'| 'chicken' | 
---------------------------- 

在表1中,行2和3將被刪除。

我試過下面的代碼,但它什麼也沒有返回。我認爲這是因爲我比較了所有的col_a,然後是所有的col_b,但不是在一起。

delete from table_1 t1 
where t1.col_a not in (select t2.col_a from table_2 t2) 
and t1.col_b not in (select t2.col_b from table_2 t2) 

回答

0

您使用||對於concatening: 應該是這樣的:

delete from table_1 t1 
where t1.col_a || '-' || t1.col_b not in (select t2.col_a || '-' || t2.col_b from table_2 t2) ; 

「 - 」是一個分隔符,最好也可以是你不應該有數據的任何字符。

SQL腳本可能是這樣的(我沒有測試,並沒有寫爲刪除代碼):

set serveroutput on; 



    DECLARE 
    CURSOR MY_CURSOR IS select * from table_1 t1 where t1.col_a || '-' || t1.col_b not in (select t2.col_a || '-' || t2.col_b from table_2 t2) ;  
    COUNTER NUMBER :=0; 
    begin 
    FOR MYCUR IN MY_CURSOR LOOP 

     BEGIN  
      -- SQL DELETE HERE 

      -- LOG : 
      DBMS_OUTPUT.PUT_LINE('row deleted'); 
      COUNTER := COUNTER + 1 ; 
      EXCEPTION WHEN OTHERS THEN 
      DBMS_OUTPUT.PUT_LINE('ERROR => ' || SQLERRM); 
      END; 
    END LOOP ; 
    DBMS_OUTPUT.PUT_LINE('Total : '||COUNTER); 
    END; 
/
+0

哦,太棒了!謝謝@ Jean-ChristopheBlanchard您是否知道如何合併DBMS_OUTPUT以便爲我提供已刪除內容的日誌? – Carlene

+0

如果你想要一個日誌,我認爲你可以創建一個遊標,並在遊標內刪除每行並輸出:CURSOR MY_CURSOR是select * from table_1 t1 where t1.col_a || ' - '|| t1.col_b不在(從table_2 t2選擇t2.col_a ||' - '|| t2.col_b); –

+0

再次感謝。我會將你的答案標記爲已接受。當你回答我的原始問題。我現在將查看與遊標相關的答案/評論,看看它是否適合我。希望我不應該需要任何進一步的幫助。你好,歡迎Carlene。 – Carlene

1

爲了達到您想要的結果,在select使用IN

這允許您在選擇中使用多個參數。

像這樣

delete from table_1 t1 
where (t1.col_a,t1.col_b) not in (select t2.col_a,t2.col_b from table_2 t2) 

更多細節約IN

+0

有趣的我不知道這種方法。 –

+0

不客氣。 –

相關問題