简体   繁体   中英

SQL, select field if field doesn't exist in another table

I have two tables, and want to get all the Products.ProductID if it doesn't exist in Images.ProductID.

I'm not too sure how I would write this..

Any help would be great.

You can translate your English sentence into SQL almost directly:

SELECT * FROM Products p
WHERE NOT EXISTS (SELECT * FROM Images i WHERE i.ProductId=p.ProductId)
select ProductID
from Products
where ProductID not in
(
  select distinct ProductID
  from images
  where ProductID is not null
)

or

select p.ProductID
from Products p
left join images i on i.ProductID = p.ProductID
where i.ProductID is null
SELECT Products.ProductID
FROM Products
WHERE Productd.ProductID NOT IN (
    SELECT Images.ProductID
    FROM Images
)
select 
     productid 
from Products 
where productid not in (select productid from Images)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM