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

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

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

任何帮助都将不胜感激。

6yjfywim

6yjfywim1#

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

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

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

uinbv5nw

uinbv5nw2#

或者,

select id from call
minus
select id from phone_number
2ledvvac

2ledvvac3#

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

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

6ljaweal

6ljaweal4#

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

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

0yycz8jy5#

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

hpxqektj6#

我想

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

sgtfey8w7#

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

uurity8g

uurity8g8#

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

相关问题