简体   繁体   中英

Excluding records based upon a one to many SQL join

How would I write a SQL query that excludes a record if one (external) record from a one to many join matches a certain condition?

For example:

Details
ID      
1         
2         

Items
DetailID    Item
1           A
1           B
2           B
2           C

How would I select the detail records where the Items do not include 'A'?

SELECT *
FROM details d
WHERE NOT EXISTS ( 
  SELECT * 
  FROM items i
  WHERE i.DetailID == d.ID 
    AND i.Item = 'A')

building on systempuntoout's solution:

SELECT details.*
FROM details 
LEFT OUTER JOIN items ON details.ID=items.DetailID AND items.Item = 'A'
WHERE items.DetailID IS NULL

Why not just using INNER JOIN like:

SELECT details.*
FROM details 
INNER JOIN items ON details.ID=items.DetailID AND items.Item<> 'A'

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