简体   繁体   中英

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 |
+----+--------+----------+

Eg 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

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.

Assuming you need each fruit name only once:

 SELECT Fruit FROM table WHERE Color IN ('green', 'yellow')
    GROUP BY Fruit HAVING COUNT(*) >= 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)...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM