Mysql: 从一个表中选择不在另一个表中的行

如何选择一个表中不出现在另一个表中的所有行?

表一:

+-----------+----------+------------+
| FirstName | LastName | BirthDate  |
+-----------+----------+------------+
| Tia       | Carrera  | 1975-09-18 |
| Nikki     | Taylor   | 1972-03-04 |
| Yamila    | Diaz     | 1972-03-04 |
+-----------+----------+------------+

表二:

+-----------+----------+------------+
| FirstName | LastName | BirthDate  |
+-----------+----------+------------+
| Tia       | Carrera  | 1975-09-18 |
| Nikki     | Taylor   | 1972-03-04 |
+-----------+----------+------------+

表1中不在表2中的行的输出示例:

+-----------+----------+------------+
| FirstName | LastName | BirthDate  |
+-----------+----------+------------+
| Yamila    | Diaz     | 1972-03-04 |
+-----------+----------+------------+

也许这样的方法可行:

SELECT * FROM Table1 WHERE * NOT IN (SELECT * FROM Table2)
244475 次浏览
SELECT *
FROM Table1 AS a
WHERE NOT EXISTS (
SELECT *
FROM Table2 AS b
WHERE a.FirstName=b.FirstName AND a.LastName=b.Last_Name
)

EXISTS会帮助你..。

您需要根据列名而不是 *执行子选择。

例如,如果两个表都有一个通用的 id字段,则可以执行以下操作:

SELECT * FROM Table1 WHERE id NOT IN (SELECT id FROM Table2)

有关更多示例,请参考 MySQL 子查询语法

标准的左连接可以解决这个问题,如果对连接字段进行索引,
也应该更快

SELECT *
FROM Table1 as t1 LEFT JOIN Table2 as t2
ON t1.FirstName = t2.FirstName AND t1.LastName=t2.LastName
WHERE t2.BirthDate Is Null

如果你有300个列,正如你在另一个注释中提到的,你想对所有的列进行比较(假设所有的列都是相同的名字) ,你可以使用一个 NATURAL LEFT JOIN来隐式地连接两个表之间所有匹配的列名,这样你就不必手动地输入所有的连接条件:

SELECT            a.*
FROM              tbl_1 a
NATURAL LEFT JOIN tbl_2 b
WHERE             b.FirstName IS NULL

试试:

SELECT * FROM table1
LEFT OUTER JOIN table2
ON table1.FirstName = table2.FirstName and table1.LastName=table2.LastName
WHERE table2.BirthDate IS NULL
SELECT a.* FROM
FROM tbl_1 a
MINUS
SELECT b.* FROM
FROM tbl_2 b

在甲骨文,这对我很有用:

SELECT a.*
FROM tbl1 a
MINUS
SELECT b.*
FROM tbl2 b;

试试这个简单的查询。

select * from Table1 where (FirstName,LastName,BirthDate) not in (select * from Table2);

一个选择是

SELECT A.*
FROM TableA as A
LEFT JOIN TableB as B
ON A.id = B.id
Where B.id Is NULL