2

I need an sql query to select a value from a table where it doesn't have a certain entry in another table. For example, considering the tables customers and customershop:

Customers

Id   Name
1    Steve
2    John
3    Bob

Customershop

CustomerId Item
1          Kiwi
1          Apple
2          Kiwi
2          Banana
3          Banana
3          Apple

I need a query for mysql so it can return Bob if looking for customers that don't have Kiwi in the customershop table. Any help is greatly appreciated.

sticky bit
  • 36,626
  • 12
  • 31
  • 42
John Doe
  • 31
  • 1
  • 2

1 Answers1

2

As your title of your question already says, use NOT EXISTS and a correlated subquery.

SELECT *
       FROM customers c
       WHERE NOT EXISTS (SELECT *
                                FROM customershop s
                                WHERE s.customerid = c.id
                                      AND s.item = 'Kiwi');
sticky bit
  • 36,626
  • 12
  • 31
  • 42