简体   繁体   中英

Need help figuring out MySQL query to count if a certain number

I have a table setup like this:

fruit1 | fruit2 | fruit3 | fruit4 | number1 | number2 | number3 | number4
--------------------------------------------------------------------------
apple  | orange | banana |  berry |    5    |    2    |    1    |    4   
orange | banana | apple  |  berry |    3    |    2    |    5    |    2
berry  | banana | orange |  apple |    1    |    2    |    5    |    2

I need a MySQL query to count how many times a given fruit is number 5. In this example, apple is 5 twice and orange is 5 once. Does that make sense? fruit1's number is number1, fruit2's number is number2, etc...

I could do this with a bit of php code but I know it's a pretty simple MySQL query. I just have the hardest time putting queries together.

Thanks in advance!

SELECT fruit, COUNT(*) NumberOfInstance
FROM
(
    SELECT fruit1 fruit, number1 num FROM table1
    UNION ALL
    SELECT fruit2 fruit, number2 num FROM table1
    UNION ALL
    SELECT fruit3 fruit, number3 num FROM table1
    UNION ALL
    SELECT fruit4 fruit, number4 num FROM table1
) s
WHERE num = 5
GROUP BY fruit

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