我有以下两个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?所需的输出将是:
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
(如其他人所说,忽略它通常最好只选择想要的列,而不是’ *‘)
*