I have 2 tables. One is people
with name, ssn, etc. The other is cars
with ssn, make, model, etc.
How would I go about selecting from the people
table where the ssn column doesn't match with any ssn from the cars
table?
The combined table has ssn, name, etc, carssn, carid
, and anyone that doesn't have a ssn on the cars
table has NULL for those 2 columns when the tables are joined.
I would use not exists
:
select p.*
from people p
where not exists (select 1 from cars c where c.ssn = p.ssn);
I would use not in
:
select *
from people
where ssn not in (select ssn from cars);
If you want to use a join, as described in the question, use is null
:
select p.*
from people p
left join cars c using (ssn)
where c.ssn is null;
It is possible to use ALL
as well
select *
from people
where ssn != ALL(select ssn from cars);
if ssn
in cars
is never NULL
. If ssn
is sometimes NULL
than you might use
select *
from people
where ssn != ALL(select ssn from cars where ssn IS NOT NULL);
You should worry about NULL
s also in solution using NOT IN
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.