我有以下两个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 | +----+------+--------------+
任何帮助将非常感激.
有几种不同的方法可以实现这一点,效率各不相同,具体取决于查询优化器的优异程度以及两个表的相对大小:
这是最短的陈述,如果您的电话簿很短,可能会最快:
SELECT * FROM Call WHERE phone_number NOT IN (SELECT phone_number FROM Phone_book)
或者(感谢Alterlife)
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
(忽略这一点,正如其他人所说,通常最好只选择你想要的列,而不是' *
')
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
应该删除子查询,允许查询优化器发挥其魔力.
另外,避免使用"SELECT*",因为如果有人改变了基础表或视图,它会破坏你的代码(并且效率很低).
在处理较大的数据集时,下面的代码比上面给出的答案更有效.
SELECT * FROM Call WHERE NOT EXISTS (SELECT 'x' FROM Phone_book where Phone_book.phone_number = Call.phone_number)
SELECT DISTINCT Call.id FROM Call LEFT OUTER JOIN Phone_book USING (id) WHERE Phone_book.id IS NULL
这将返回Phone_book表中缺少的额外id-s.