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

后端 未结 8 850
生来不讨喜
生来不讨喜 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 23:20

    The code below would be a bit more efficient than the answers presented above when dealing with larger datasets.

    SELECT * FROM Call WHERE 
    NOT EXISTS (SELECT 'x' FROM Phone_book where 
    Phone_book.phone_number = Call.phone_number)
    
    0 讨论(0)
  • 2020-11-21 23:22
    SELECT Call.ID, Call.date, Call.phone_number 
    FROM Call 
    LEFT OUTER JOIN Phone_Book 
      ON (Call.phone_number=Phone_book.phone_number) 
      WHERE Phone_book.phone_number IS NULL
    

    Should remove the subquery, allowing the query optimiser to work its magic.

    Also, avoid "SELECT *" because it can break your code if someone alters the underlying tables or views (and it's inefficient).

    0 讨论(0)
提交回复
热议问题