开发者

filtering for multiple values on one column based on values from another column

Previously I asked about filtering one column for multiple v开发者_如何学Calues where all of them must be present in the column, otherwise no results should be given. I recieved good answer, but this time my request changed somewhat and i need something different.

So I need to filter one column for couple values and show results only if all those values are there AND all those values are related to one value in another column.

Example table:

+----+--------+----------+

| id | Fruit | Color |

+----+--------+----------+

| 1 | apple | green |

| 2 | apple | yellow |

| 3 | banana | green |

| 4 | banana | yellow |

| 5 | mango | green |

+----+--------+----------+

E.g. if values 'green and yellow' are submitted, only fruits that have both of these colors should be in the result set, in this case 'apple' and 'banana'. All other rows should be dismissed.

I am using MySQL with php.

Example "wrong code":

select Fruit FROM table WHERE Color = green AND Color = yellow 

Must return first 4 rows but not 5.

Thank you

Andrew


Assuming you need each fruit name only once:

 SELECT Fruit FROM table WHERE Color IN ('green', 'yellow')
    GROUP BY Fruit HAVING COUNT(*) >= 2


So, in that case, you need all (fruit,color) pairs that appear exactly twice. You can use a count to filter that out, like so:

select fruit from( select fruit,count(1) as freq from table where color in (green,yellow) group by 1 )freq_table where freq=2;

This, of course, assumes that no (fruit,color) pair appears more than once. If so, then you might want a third level of subquerying where you select fruit,color from table group by 1,2.


Well, you'll want to join the table on itself.

SELECT a.Fruit 
FROM table AS a
JOIN table AS b ON a.Fruit = b.Fruit
WHERE a.Color = 'green'
    AND b.Color = 'yellow'

But, instead, I'd suggest properly normalizing your data, which would make this query much easier (and much more efficient)...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜