我有2个表。一个是people
有名字,SSN等。另一种是用cars
SSN,品牌,型号等SQL选择其中值不匹配
我怎么会去从people
表所在的SSN列不从任何SSN匹配选择cars
表?
组合表具有ssn, name, etc, carssn, carid
,任何在cars
表中没有ssn的人在连接表时对于这2列都有NULL。
我有2个表。一个是people
有名字,SSN等。另一种是用cars
SSN,品牌,型号等SQL选择其中值不匹配
我怎么会去从people
表所在的SSN列不从任何SSN匹配选择cars
表?
组合表具有ssn, name, etc, carssn, carid
,任何在cars
表中没有ssn的人在连接表时对于这2列都有NULL。
我会用not exists
:
select p.*
from people p
where not exists (select 1 from cars c where c.ssn = p.ssn);
我会用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;
也可以使用ALL
select *
from people
where ssn != ALL(select ssn from cars);
如果ssn
在cars
从来都不是NULL
。如果ssn
有时NULL
可能比你使用
select *
from people
where ssn != ALL(select ssn from cars where ssn IS NOT NULL);
你应该使用担心NULL
S还溶液NOT IN