Mysql query to find ID where multiple condition meet for one column

痞子三分冷 提交于 2021-02-08 03:30:44

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!