如何检索两个表中不常见的行

时间:2014-03-25 10:49:46

标签: mysql sql

我有两张桌子:

tata_data1:

Password | Region | Company | System
-------------------------------------
a02040   | Del    | xx      | abc
a01917   | Mum    | xxx     | pqr
a01916   | Mum    | x       | zzz
a01906   | Nag    | x       | pny

tata_passwords:

Password | Region | Company
----------------------------
a02049   | Nag    | xxxx
a01917   | Mum    | xxx
a01000   | Del    | xx
a01906   | Nag    | x

我想只从tata_passwords中获取那些行,这些行在tata_data1中不存在。将密码视为主键。

3 个答案:

答案 0 :(得分:1)

使用LEFT OUTER JOIN: -

SELECT  tata_passwords.*
FROM  tata_passwords
LEFT OUTER JOIN tata_data1
ON tata_passwords.Password = tata_data1.Password
WHERE tata_data1.Password IS NULL

答案 1 :(得分:0)

试试这个:

SELECT * FROM tata_passwords WHERE (Password, Region, Company) NOT IN ( SELECT Password, Region, Company FROM tata_data1 )

修改

现在,当密码是主键时,可以将查询缩减为:

SELECT * FROM tata_passwords WHERE Password NOT IN ( SELECT Password FROM tata_data1 )

答案 2 :(得分:0)

select * 
from tata_passwords 
where tata_passwords.password NOT IN (select password from tata_data1)

或者您可以使用 Mr.Kickstart 表示LEFT OUTER JOIN

SELECT tata_passwords.*
FROM tata_passwords LEFT OUTER JOIN tata_data1 ON tata_passwords.password=tata_data1.password 
where tata_data1.password IS NULL