2017-10-17 67 views
0

我有2个表。一个是people有名字,SSN等。另一种是用cars SSN,品牌,型号等SQL选择其中值不匹配

我怎么会去从people表所在的SSN列不从任何SSN匹配选择cars表?

组合表具有ssn, name, etc, carssn, carid,任何在cars表中没有ssn的人在连接表时对于这2列都有NULL。

回答

4

我会用not exists

select p.* 
from people p 
where not exists (select 1 from cars c where c.ssn = p.ssn); 
0

我会用not in

select * 
from people 
where ssn not in (select ssn from cars); 

如果你想使用一个连接,如问题描述,使用is null

select p.* 
from people p 
left join cars c using (ssn) 
where c.ssn is null; 
0

也可以使用ALL

select * 
from people 
where ssn != ALL(select ssn from cars); 

如果ssncars从来都不是NULL。如果ssn有时NULL可能比你使用

select * 
from people 
where ssn != ALL(select ssn from cars where ssn IS NOT NULL); 

你应该使用担心NULL S还溶液NOT IN