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

bqf10yzr  于 2021-06-15  发布在  Mysql
关注(0)|答案(8)|浏览(244)

我有以下两个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 |
+----+------+--------------+

任何帮助都将不胜感激。

jjjwad0x

jjjwad0x1#

当处理更大的数据集时,下面的代码将比上面给出的答案更有效率。

SELECT * FROM Call WHERE 
NOT EXISTS (SELECT 'x' FROM Phone_book where 
Phone_book.phone_number = Call.phone_number)
j2cgzkjk

j2cgzkjk2#

或者,

select id from call
minus
select id from phone_number
l7mqbcuq

l7mqbcuq3#

我想

SELECT CALL.* FROM CALL LEFT JOIN Phone_book ON 
CALL.id = Phone_book.id WHERE Phone_book.name IS NULL
zf2sa74q

zf2sa74q4#

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
wooyq4lh

wooyq4lh5#

SELECT name, phone_number FROM Call a
WHERE a.phone_number NOT IN (SELECT b.phone_number FROM Phone_book b)
e1xvtsh3

e1xvtsh36#

SELECT DISTINCT Call.id 
FROM Call 
LEFT OUTER JOIN Phone_book USING (id) 
WHERE Phone_book.id IS NULL

这将返回电话簿表中丢失的额外id。

rmbxnbpk

rmbxnbpk7#

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*”,因为如果有人修改底层的表或视图,它会破坏代码(而且效率很低)。

zqdjd7g9

zqdjd7g98#

有几种不同的方法可以做到这一点,效率各不相同,这取决于您的查询优化程序有多好,以及两个表的相对大小:
这是最短的语句,如果您的电话簿很短,这可能是最快的语句:

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

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

相关问题