Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL selection over two rows

How do I select in a table like below all objects that have a-A and b-B (as key-value pair)?

Something like:

SELECT DISTINCT(OBJECT) 
  FROM MYTABLE 
 WHERE key = 'a' 
   AND value = 'A' 
   AND key = 'b' 
   AND value = 'B'

...where the result would be 1 and 3.

I know that this SQL statement doesn't work, but I hope it explains a bit what I want to do.

And sorry for the diffuse title. I simply don't know how to describe the problem better.

object | key | value
---------------------
1   |  a  |   A
1   |  b  |   B
1   |  c  |   C
2   |  a  |   F
2   |  b  |   B
3   |  a  |   A
3   |  b  |   B
3   |  d  |   D
like image 522
Zardoz Avatar asked Dec 10 '25 04:12

Zardoz


1 Answers

I think you want something of this form:

SELECT a.object 
FROM mytable a, mytable b 
WHERE a.object = b.object 
  AND a.key = 'a' AND a.value = 'A'
  AND b.key = 'b' AND b.value = 'B'
like image 185
Mark Elliot Avatar answered Dec 12 '25 18:12

Mark Elliot



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!