Mysql
 SQL >> Database >  >> RDS >> Mysql

Trovare righe padre che corrispondono a più valori contemporaneamente

L'aggregazione condizionale è la strada più diretta:

select parentid from tablename group by parentid having sum(case when datavalue = 1 then 1 else 0 end) > 0 and sum(case when datavalue = 6 then 1 else 0 end) > 0

Oppure esprimi lo stesso intento con una coppia di controlli exists:

select distinct parentid from tablename t1 where exists (select * from tablename where parentid = t1.parentid and datavalue = 1) and exists (select * from tablename where parentid = t1.parentid and datavalue = 6)

E se potresti estendere l'elenco in futuro, contare le corrispondenze distinte scala meglio:

select parentid from tablename where datavalue in (1, 6) group by parentid having count(distinct datavalue) = 2