小编典典

从一个表中查找另一个表中不存在的记录

sql

我有以下两个表(在MySQL中):

Phone_book
+----+------+--------------+
| id | name | phone_number |
+----+------+--------------+
| 1  | John | 111111111111 |
+----+------+--------------+
| 2  | Jane | 222222222222 |
+----+------+--------------+

Call
+----+------+--------------+
| id | date | phone_number |
+----+------+--------------+
| 1  | 0945 | 111111111111 |
+----+------+--------------+
| 2  | 0950 | 222222222222 |
+----+------+--------------+
| 3  | 1045 | 333333333333 |
+----+------+--------------+

如何找出哪些电话是由人,他们提出phone_number是不是在Phone_book?所需的输出将是:

Call
+----+------+--------------+
| id | date | phone_number |
+----+------+--------------+
| 3  | 1045 | 333333333333 |
+----+------+--------------+

阅读 203

收藏
2021-05-05

共1个答案

小编典典

有几种不同的方法可以执行此操作,效率各不相同,具体取决于查询优化器的性能以及两个表的相对大小:

这是最简短的陈述,如果您的电话簿很短,则可能是最快的陈述:

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






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

或(感谢WOPR)

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

(忽略这一点,正如其他人所说的那样,通常最好只选择所需的列,而不是’ *‘)

2021-05-05