Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excluding records based upon a one to many SQL join

Tags:

sql

sql-server

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'?

like image 372
Paul Ellery Avatar asked Apr 08 '10 09:04

Paul Ellery


People also ask

How do I exclude multiple records in SQL?

To exclude multiple values to be fetched from a table we can use multiple OR statements but when we want to exclude a lot of values it becomes lengthy to write multiple AND statements, To avoid this we can use the NOT IN clause with the array of values that need to be excluded with the WHERE statement.

What does (+) mean in SQL joins?

The plus sign is Oracle syntax for an outer join. There isn't a minus operator for joins. An outer join means return all rows from one table. Also return the rows from the outer joined where there's a match on the join key. If there's no matching row, return null.

Which join does not require matching records?

When you use a simple (INNER) JOIN , you'll only get the rows that have matches in both tables. The query will not return unmatched rows in any shape or form. If this is not what you want, the solution is to use the LEFT JOIN , RIGHT JOIN , or FULL JOIN , depending on what you'd like to see.

Is there an exclude function in SQL?

Introduction to SQL EXCLUDE. In SQL, in order to EXCLUDE certain rows from being returned by a SELECT query, we use some restricting or excluding conditions based on some criteria. EXCLUDE conditions in SQL usually appear in the WHERE clause of the statement or in the HAVING clause of an aggregate query.


2 Answers

SELECT *
FROM details d
WHERE NOT EXISTS ( 
  SELECT * 
  FROM items i
  WHERE i.DetailID == d.ID 
    AND i.Item = 'A')
like image 52
Stefan Steinegger Avatar answered Sep 30 '22 07:09

Stefan Steinegger


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
like image 37
devio Avatar answered Sep 30 '22 08:09

devio