HiveBrain v1.2.0
Get Started
← Back to all entries
patternModerate

Self Join? Or am I wrong?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
wrongjoinself

Problem

We have a table that we use to store customers and items. We need to be able to find customers that have bought one item and have not bought another item:

customer     item  
Sally        1   
Sally        2  
Sally        3
John         1  
John         2  
Paul         2
Paul         3


We want to find users who bought "1" and not "3". In this case we only want "John".

Solution

No, a self join would not really help, but if your database system has an EXCEPT operator (or something similar, in Oracle it is called MINUS) it would.

Here's how you get your result:

SELECT customer FROM Sales
WHERE item = 1
AND customer NOT IN (SELECT customer FROM Sales WHERE item = 3)


If you have an EXCEPT operator:

SELECT customer FROM Sales WHERE item = 1
EXCEPT
SELECT customer FROM Sales WHERE item = 3

Code Snippets

SELECT customer FROM Sales
WHERE item = 1
AND customer NOT IN (SELECT customer FROM Sales WHERE item = 3)
SELECT customer FROM Sales WHERE item = 1
EXCEPT
SELECT customer FROM Sales WHERE item = 3

Context

StackExchange Database Administrators Q#80322, answer score: 10

Revisions (0)

No revisions yet.