0

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?

2 Answers 2

2
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
Sign up to request clarification or add additional context in comments.

1 Comment

Now, what if the question was p='A' and p='B' AND p='C'. Or even better, p in any of ['A','B','C',...] ?
1

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.