How to find rows in one table that have no corresponding row in another table

后端 未结 6 742
甜味超标
甜味超标 2020-11-29 01:50

I have a 1:1 relationship between two tables. I want to find all the rows in table A that don\'t have a corresponding row in table B. I use this query:

SELEC         


        
6条回答
  •  一整个雨季
    2020-11-29 02:17

    For my small dataset, Oracle gives almost all of these queries the exact same plan that uses the primary key indexes without touching the table. The exception is the MINUS version which manages to do fewer consistent gets despite the higher plan cost.

    --Create Sample Data.
    d r o p table tableA;
    d r o p table tableB;
    
    create table tableA as (
       select rownum-1 ID, chr(rownum-1+70) bb, chr(rownum-1+100) cc 
          from dual connect by rownum<=4
    );
    
    create table tableB as (
       select rownum ID, chr(rownum+70) data1, chr(rownum+100) cc from dual
       UNION ALL
       select rownum+2 ID, chr(rownum+70) data1, chr(rownum+100) cc 
          from dual connect by rownum<=3
    );
    
    a l t e r table tableA Add Primary Key (ID);
    a l t e r table tableB Add Primary Key (ID);
    
    --View Tables.
    select * from tableA;
    select * from tableB;
    
    --Find all rows in tableA that don't have a corresponding row in tableB.
    
    --Method 1.
    SELECT id FROM tableA WHERE id NOT IN (SELECT id FROM tableB) ORDER BY id DESC;
    
    --Method 2.
    SELECT tableA.id FROM tableA LEFT JOIN tableB ON (tableA.id = tableB.id)
    WHERE tableB.id IS NULL ORDER BY tableA.id DESC;
    
    --Method 3.
    SELECT id FROM tableA a WHERE NOT EXISTS (SELECT 1 FROM tableB b WHERE b.id = a.id) 
       ORDER BY id DESC;
    
    --Method 4.
    SELECT id FROM tableA
    MINUS
    SELECT id FROM tableB ORDER BY id DESC;
    

提交回复
热议问题