[英]sql - compare table
如何比較兩個表並根據結果做出反應。 例如,我有2個表(精確的結構):tableA(鍵,文本)和tableB(鍵,文本)以及結果表(鍵,字段,大小寫)。
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;
我認為您需要這樣的東西:
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
祝好運。
這會有所幫助嗎?
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.