Reputation: 57
Ok, this seems like it should be an easy one so I will try to simplify what I am trying to do.
Say I have this select statement:
SELECT a.customer, b.fruit
FROM Customer a
INNER JOIN Order b ON a.customer = b.Customer
Which would return the following:
Customer Fruit
-------------------------
Jane Apple
Jane Banana
Bob Apple
Bob Orange
Bob Grape
John Apple
John Banana
Ann Tangerine
Ann Orange
Ann Banana
What I would like to pull from this result set is a list of customers who have never ordered, say, a 'Tangerine', resulting in the following list:
Customer
--------
Jane
Bob
John
How would one go about do this? Thanks in advance!
Upvotes: 1
Views: 68
Reputation: 45096
Existing answers are missing distinct customers
SELECT distinct c.customer
FROM Customer c
WHERE NOT EXISTS ( SELECT 1
FROM Customer T
WHERE T.customer = c.customer
And T.Fruit = 'Tangerine'
);
And I don't like tables and column the same
That would be more and Order table
Upvotes: 0
Reputation: 70658
There are many ways to do this:
SELECT *
FROM Customer c
WHERE NOT EXISTS(SELECT 1 FROM Order
WHERE customer = c.customer
And Fruit = 'Tangerine');
Using NOT IN
:
SELECT *
FROM Customer c
WHERE c.Customer NOT IN (SELECT Customer FROM Order
WHERE Customer IS NOT NULL
And Fruit = 'Tangerine');
Upvotes: 2
Reputation: 1270391
Here is one method using left join
:
SELECT c.customer
FROM Customer c LEFT JOIN
Order o
ON c.customer = o.Customer AND o.fruit = 'Tangerine'
WHERE o.Customer IS NULL;
Upvotes: 1