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

2021-11-20 00:00:00 sorting unique mysql database-table

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

How to select all rows in one table that do not appear on another?

表 1:

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

表 2:

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

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

Example output for rows in Table1 that are not in Table2:

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

也许这样的事情应该可行:

Maybe something like this should work:

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

推荐答案

如果您在另一条评论中提到有 300 列,并且您想对所有列进行比较(假设所有列的名称相同),您可以使用 NATURAL LEFT JOIN 隐式连接两个表之间所有匹配的列名,这样您就不必手动输入所有连接条件:

If you have 300 columns as you mentioned in another comment, and you want to compare on all columns (assuming the columns are all the same name), you can use a NATURAL LEFT JOIN to implicitly join on all matching column names between the two tables so that you don't have to tediously type out all join conditions manually:

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

相关文章