2014-02-08 94 views
1

這個概念是,我試圖比較兩個等值表,以查看其他查詢是否具有相同的值或者它們是否存在於另一個查詢中。 我加入表的方式是: 「select a.sth,a.sth2,a.st3,b.value for table1 a,table2 b where a.key = b.valkey」 這將導致顯示值table1的列和接下來來自table2的列值2,其中鍵是相同的。 現在我有另外2個表中包含類似的數據,我想檢查我的查詢結果是否存在於我將爲其他表建立的查詢中: 「select a.sth,a.sth2,a.st3, b.value for table3 a,table4 b其中a.key = b.valkey「Oracle比較2個等值表

我認爲這樣做的唯一方法是使用嵌套隱式遊標。例如:

BEGIN 
    FOR item IN (select a.sth, a.sth2, a.st3, b.value for table1 a, table2 b where a.key = b.valkey) 
    LOOP 
Begin 
FOR item2 IN (select a.sth, a.sth2, a.st3, b.value for table3 a, table4 b where a.key = b.valkey) 
    LOOP 
    Begin 
if (item1.sth = item2.sth) and (item1.sth2 = item2.sth2) and (item1.sth3 = item2.sth3) and (item1.value = item2.value) Then 
dbms_output.put_line("Found and value is the same"); 
Elsif (item1.sth = item2.sth) and (item1.sth2 = item2.sth2) and (item1.sth3 = item2.sth3) and Not (item1.value = item2.value) Then 
dbms_output.put_line("Found but value is different"); 
Exception When no_data_found then 
dbms_output.put_line("item1 was not found in table3"); 
End; 
    END LOOP; 
End; 
END LOOP; 
END; 

以上只是我想要做的僞代碼。我可以做這樣的事情嗎?或者有更好的表現可供選擇嗎?我期待着你的建議。

回答

1

你不需要這個遊標。一般來說,基於集合的代碼會更好地工作。查詢會是這個樣子:

select coalesce(a.key, b.valkey) as thekey, 
     a.sth, a.sth2, a.st3, b.value 
     (case when a.key is null then 'Not found in a' 
      when b.key is null then 'Not found in b' 
      when (a.sth = b.sth) and (a.sth2 = b.sth2) and (a.sth3 = b.sth3) and 
        (a.value = b.value) 
      then 'Found and same' 
      when (a.sth = b.sth) and (a.sth2 = b.sth2) and (a.sth3 = b.sth3) and 
        (a.value <> b.value) 
      then 'Found and different' 
      else 'Other!!!' 
     end) 
from table1 a full outer join 
    table2 b 
    on a.key = b.valkey 
+0

我很抱歉,我不明白這是怎樣能幫助我..這個概念是,我已經是基於價值加入一方面2個表。 –

+0

@GeorgeGeorgiou。 。 。這個查詢幾乎完成了PL/SQL代碼的工作,除了它使用SQL而不是遊標。這應該會讓它跑得更快。 –

+0

因此,這將檢查前兩個表(1,2)的組合值是否存在於另外兩個表(3,4)中,以及它們是否具有相同的值?我正在嘗試閱讀文檔,但我很困惑這件事情是如何發生的 –