问题
I would appreciate any help creating this query. I have tried several methods without luck. As my question is somewhat difficult for me to phrase, I will make a simple example of what I want to do. I have data that is structurally similar to the following:
ID TYPE COLOR
1 A Blue
1 B Red
1 C Green
2 C Blue
2 B Green
I want to create a query to return the types if I have an ID with two specific colors. For example I would like to find all the ID that have both Blue and Red. The query would then return:
1, A , B
The order that A and B is returned is unimportant. The data set is large, I expect many ID's to match both conditions( maybe 50,000 or so). I should note that the type does not correlate to color thus making the problem different from this other stackoverflow question,as well as this one.
I think I need to do a subquery of some sort. But really don't know how to proceed, Thank you.
回答1:
SELECT ID, TYPE FROM types NATURAL JOIN (
SELECT ID FROM types GROUP BY ID HAVING SUM(COLOR='Red') AND SUM(COLOR='Blue')
) t WHERE COLOR IN ('Red', 'Blue')
See it on sqlfiddle.
Alternatively, if you're happy to have the types concatenated into a delimited string, you can extract the desired data in a single pass:
SELECT ID, GROUP_CONCAT(TYPE)
FROM types
WHERE COLOR IN ('Red', 'Blue')
GROUP BY ID
HAVING COUNT(*) = 2
See it on sqlfiddle.
Note that, if your table might contain multiple records with the same (ID, COLOR)
pair, you should replace COUNT(*)
with the more expensive COUNT(DISTINCT COLOR)
.
来源:https://stackoverflow.com/questions/13299670/mysql-query-to-find-id-where-multiple-condition-meet-for-one-column