MySQL : Select records with conditions that applie

2019-09-21 08:50发布

问题:

I have a table:

DETAILS

--------------------------------------------------------
ID    |   PARENT_ID    |    DATA_KEY     |   DATA_VALUE
======================================================== 
1     |      1         |     Guitar      |      4
--------------------------------------------------------
2     |      1         |     Radio       |      2
--------------------------------------------------------
3     |      1         |     Tv          |      2
--------------------------------------------------------
4     |      1         |     Drum Kit    |      3
--------------------------------------------------------
5     |      2         |     Guitar      |      4
--------------------------------------------------------
6     |      2         |     Radio       |      2
--------------------------------------------------------
7     |      2         |     Tv          |      2
--------------------------------------------------------
8     |      2         |     Drum Kit    |      3
--------------------------------------------------------
9     |      3         |     Guitar      |      1
--------------------------------------------------------
10    |      3         |     Radio       |      2
--------------------------------------------------------
11    |      3         |     Tv          |      2
--------------------------------------------------------
12    |      3         |     Drum Kit    |      3
--------------------------------------------------------

How do i select in mysql distinct PARENT_ID that satisfies the below conditions:

    1. DATA_KEY = 'Guitar' and DATA_VALUE = '4'
    1. DATA_KEY = 'Radio' and DATA_VALUE = '2'

Expected output of the query should be

-------------
PARENT_ID
=============
  1
-------------
  2
-------------

Since only PARENT_ID 1 and 2 has 'Guitar' = '4' and 'Radio' = '2'

回答1:

SELECT DISTINCT a.parent_id 
FROM details AS a
JOIN details AS b ON a.parent_id=b.parent_id
WHERE a.data_key='Guitar' AND a.data_value='4' AND
      b.data_key='Radio' AND b.data_value='2';


回答2:

SELECT DISTINCT Parent_Id
FROM details
WHERE (data_key='Guitar' AND data_value='4') OR
(data_key='Radio' AND data_value='2')

That will get the results you requested.

What you commented as having tried was close, but it was using an 'AND' instead of an 'OR'.



回答3:

maybe you look for this

   SELECT  a.parent_id 
  FROM details AS a
  JOIN details AS b ON a.parent_id=b.parent_id
  WHERE a.data_key='Guitar' AND a.data_value='4' AND
     b.data_key='Radio' AND b.data_value='2'
  group by a.parent_id ;

demo here