SQL - find records from one table which don't exist in another

后端 未结 8 849
生来不讨喜
生来不讨喜 2020-11-21 22:44

I\'ve got the following two SQL tables (in MySQL):

Phone_book
+----+------+--------------+
| id | name | phone_number |
+----+------+--------------+
| 1  | J         


        
相关标签:
8条回答
  • 2020-11-21 22:57

    Alternatively,

    select id from call
    minus
    select id from phone_number
    
    0 讨论(0)
  • 2020-11-21 22:58

    There's several different ways of doing this, with varying efficiency, depending on how good your query optimiser is, and the relative size of your two tables:

    This is the shortest statement, and may be quickest if your phone book is very short:

    SELECT  *
    FROM    Call
    WHERE   phone_number NOT IN (SELECT phone_number FROM Phone_book)
    

    alternatively (thanks to Alterlife)

    SELECT *
    FROM   Call
    WHERE  NOT EXISTS
      (SELECT *
       FROM   Phone_book
       WHERE  Phone_book.phone_number = Call.phone_number)
    

    or (thanks to WOPR)

    SELECT * 
    FROM   Call
    LEFT OUTER JOIN Phone_Book
      ON (Call.phone_number = Phone_book.phone_number)
      WHERE Phone_book.phone_number IS NULL
    

    (ignoring that, as others have said, it's normally best to select just the columns you want, not '*')

    0 讨论(0)
  • 2020-11-21 22:58
    SELECT t1.ColumnID,
    CASE 
        WHEN NOT EXISTS( SELECT t2.FieldText  
                         FROM Table t2 
                         WHERE t2.ColumnID = t1.ColumnID) 
        THEN t1.FieldText
        ELSE t2.FieldText
    END FieldText       
    FROM Table1 t1, Table2 t2
    
    0 讨论(0)
  • 2020-11-21 23:00
    SELECT DISTINCT Call.id 
    FROM Call 
    LEFT OUTER JOIN Phone_book USING (id) 
    WHERE Phone_book.id IS NULL
    

    This will return the extra id-s that are missing in your Phone_book table.

    0 讨论(0)
  • 2020-11-21 23:00

    I think

    SELECT CALL.* FROM CALL LEFT JOIN Phone_book ON 
    CALL.id = Phone_book.id WHERE Phone_book.name IS NULL
    
    0 讨论(0)
  • 2020-11-21 23:00
    SELECT name, phone_number FROM Call a
    WHERE a.phone_number NOT IN (SELECT b.phone_number FROM Phone_book b)
    
    0 讨论(0)
提交回复
热议问题