Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all IDs which have a row with value A AND a row with value B

I have a table like this:

+-----+-------+-----+
| id  | value | ... |
+-----+-------+-----+
| 1   | A     | ... |
| 1   | B     | ... |
| 1   | C     | ... |
| 2   | B     | ... |
| 2   | C     | ... |
| 3   | A     | ... |
| 3   | C     | ... |
| 4   | B     | ... |
| 4   | A     | ... |
| ... | ...   | ... |
+-----+-------+-----+

I want to limit this to just ids that have both rows with A and rows with B in the value column. In this case, the table would look like this:

+-----+-------+-----+
| id  | value | ... |
+-----+-------+-----+
| 1   | A     | ... |
| 1   | B     | ... |
| 1   | C     | ... |
| 4   | B     | ... |
| 4   | A     | ... |
| ... | ...   | ... |
+-----+-------+-----+

… because neither id 2 nor 3 had both A and B in the value column.

Is there a succinct way to locate these IDs?

like image 864
Andrew LaPrise Avatar asked Jan 30 '26 21:01

Andrew LaPrise


1 Answers

select id, value
from t
where id in (
    select id
    from t
    group by id
    having bool_or(value = 'A') and bool_or(value = 'B')
)

or

select id, value
from t t0
where 
    exists (
        select 1
        from t
        where id = t0.id and value = 'A'
    ) and
    exists (
        select 1
        from t
        where id = t0.id and value = 'B'
    ) 
like image 145
Clodoaldo Neto Avatar answered Feb 02 '26 12:02

Clodoaldo Neto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!