0
customer id | hobby

I would like to use mysql query to extract customers which have the same hobbies.
If someone has more hobbies we have one row for each hobby.

It is easy to use

SELECT customer_id 
FROM customers
WHERE hobby='football'

My problem is that I want to search for two hobbies.

For example 'football' and 'swimming' and the query must result only the customers which have both.

Is it possible to do it with query or should I use stored procedure and how ?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • WHERE IN () GROUP BY HAVING COUNT(*) = number of items in IN() – Strawberry Apr 21 '14 at 15:25
  • possible duplicate of [How to return rows that have the same column values in MySql](http://stackoverflow.com/questions/16704290/how-to-return-rows-that-have-the-same-column-values-in-mysql) – Barmar Apr 21 '14 at 15:27
  • Do you want customers who have *only* those two hobbies, or *at least* those two hobbies? – Bohemian Apr 29 '14 at 14:06

1 Answers1

0
SELECT customer_id 
FROM customers 
WHERE hobby in ('swimming','football')
group by custimer_id
having count(distinct hobby) = 2

SQLFiddle demo

juergen d
  • 201,996
  • 37
  • 293
  • 362