How can I select mysql data with a union statement where the data matches each select statement, i.e. combine the AND operator with UNION?

StackOverflow https://stackoverflow.com/questions/8952330

Question

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.

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top