Andrew
Andrew

Reputation: 528

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

Previously I asked about filtering one column for multiple values 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

Upvotes: 1

Views: 9277

Answers (3)

Larry Lustig
Larry Lustig

Reputation: 50970

Assuming you need each fruit name only once:

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

Upvotes: 2

user554546
user554546

Reputation:

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.

Upvotes: 1

ircmaxell
ircmaxell

Reputation: 165201

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)...

Upvotes: 0

Related Questions