简体   繁体   中英

MySQL selecting values based on multiple rows

I have a MySQL table like so;

foo      bar
1        21
23       17
31       17
23       21
19       9
23       4
31       4
3        27
51       6
31       44
23       44
31       71

What I want is to select all the unique values of bar that correspond to both 23 and 31 in the foo column.

ie for this table, I'd get the following result;

bar
17
4
44

17 , 4 , and 44 all get selected, since for all of those values, two rows exist that correspond to both 23 and 31 in the foo column.

Even though the values 21 and 71 in bar correspond to 23 and 31 in foo , they would not get selected, since the same value of bar isn't present on another row that would correspond to the other number.

How would I go about this?

SELECT 
    bar
FROM 
    tbl
WHERE
    foo IN (23,31)
GROUP BY
    bar
HAVING
    COUNT(*) = 2

The 2 in COUNT(*) represents the amount of values of foo you're checking on — in this case, two. If you wanted bar s corresponding to all of (23,31,7) for example, change it to COUNT(*) = 3 because there are three values to satisfy.

Try this ::

Select tab1.bar
from
(select bar from table where foo=/*?(say 23)*/) tab1
inner join 
(Select bar from table where foo=/*?(say 31)*/) tab2
on (tab1.bar=tab2.bar)

How about this?

SELECT bar
FROM mytable
WHERE foo IN (23,31)
GROUP BY bar
HAVING count(bar) >= 2

Demo

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