简体   繁体   中英

MySQL query count multiple values

Consider the following DB table:

c     p
=========
1     'a'
1     'b'
2     'a'
2     'c'

Now, my goal is to retrieve a list of numbers c, for which holds that each number in this list has at least a record with p='a' AND p='b'.

In the example table above, that would be c=1.

Now my question is, how do I accomplish this using one MySQL query?

select t1.c
from MyTable t1
inner join MyTable t2 on t1.c = t2.c
where t1.p = 'a' and t2.p = 'b'

Update:

select c
from MyTable 
where p in ('a', 'b', 'c', 'd')
group by c
having count(distinct p) = 4

There are different ways to attack the problem depending on the rules your data follows if any. Without knowing more about your problem, I would do:

SELECT t1.c FROM table t1 INNER JOIN table t2
  ON t1.c = t2.c
  WHERE t1.p = 'a' AND t2.p = 'b'

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