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

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

表格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中的行的示例输出:

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

也许这样的事情应该工作:

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

如果您在另一条评论中提到了300列,并且想要在所有列上进行比较(假设列的名称都是相同的),则可以使用NATURAL LEFT JOIN隐式地连接两个表之间的所有匹配列名所以你不必手工input所有的连接条件:

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

您需要根据列名进行子select,而不是*

例如,如果你有一个两个表共有的id字段,你可以这样做:

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

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

一个标准的LEFT JOIN可以解决这个问题, 如果join上的字段被索引,
也应该更快

 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 
 Select * FROM Table1 as a WHEre NOT EXISTS(Select * FROM Table2 as b WHERE a.FirstName =b.FirstName and a.LastName=b.Last_Name ) 

存在将帮助你…

尝试:

 SELECT * FROM table1 LEFT OUTER JOIN table2 ON table1.FirstName = table2.FirstName and table1.LastName=table2.LastName WHERE table2.BirthDate IS NULL 

这在Oracle中适用于我:

 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 FROM tbl_1 a MINUS SELECT b.* FROM FROM tbl_2 b