Lets say I have a table with just two columns: name and mood. A row holds a persons name, and their mood, if they have multiple moods, then multiple rows are stored in the DB.
For example, in the database is John, who is happy, excited, and proud.
This is represented as
John Happy
John Excited
John Proud
What I want to do is select the name based on several moods being met. Similiar to the UNION:
SELECT name WHERE mood=Happy
UNION
SELECT name WHERE mood=Excited
UNION
SELECT name WHERE mood=Proud
However using the above union would result in:
John
John
John
Union all would result in one single result of John, but it would also select any names that only match one of the queries.
I can think of a few algorithms which would take each individual mysql_result resource (I'm using PHP), and look for matching results, but what I want to know is whether MySQL already facilitates this.
I realise the above is quite a vague generalisation, needless to say my actual program is alot more complicated and I've dumbed it down a little for this question, please don't hesitate to ask questions.
Provided you have no duplicates, you can do it with a subquery:
SELECT `name` FROM (
SELECT `name`, COUNT(*) AS `count` FROM `moods`
WHERE `mood` IN ('Excited', 'Happy', 'Proud') GROUP BY `name`
) WHERE `count` = 3
Alternatively, you can use join:
SELECT `m1`.`name` FROM `moods` `m1`
JOIN `moods` `m2` USING (`name`)
JOIN `moods` `m3` USING (`name`)
WHERE `m1`.`mood` = 'Excited' AND `m2`.`mood` = 'Happy' AND `m3`.`mood` = 'Proud'
Not so cute, but might be faster if you use LIMIT. Or maybe not. Depends a lot on query planner.
UPD: thanks to Tudor Constantin for reminding me about HAVING, the first query can then be:
SELECT `name` FROM `moods`
WHERE `mood` IN ('Excited', 'Happy', 'Proud')
GROUP BY `name`
HAVING COUNT(*)>3