简体   繁体   中英

sql - compare table

How can I compare two tables and react depending on the result. Eg I have 2 tables (exact structure): tableA(key, text) and tableB(key, text) and a result table (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

the result table looks like:

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

Is it possible to do it with just one query?

to get insert (and vice versa for delete):

SELECT key FROM tableA
MINUS
SELECT key FROM tableB;

I think you need something like this:

  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'
  )

You can find some examples and variations of this concept in the link: http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1004115105172

Good luck.

Would this help?

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM