-1

我有一张桌子:

细节

--------------------------------------------------------
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
--------------------------------------------------------

如何在 mysql 中选择满足以下条件的不同 PARENT_ID:

    1. DATA_KEY = '吉他' 和 DATA_VALUE = '4'
    1. DATA_KEY = '收音机' 和 DATA_VALUE = '2'

查询的预期输出应该是

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

因为只有 PARENT_ID 1 和 2 有 'Guitar' = '4' 和 'Radio' = '2'

4

3 回答 3

5
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';
于 2013-03-04T18:07:00.550 回答
0
SELECT DISTINCT Parent_Id
FROM details
WHERE (data_key='Guitar' AND data_value='4') OR
(data_key='Radio' AND data_value='2')

这将得到您要求的结果。

您所评论的尝试很接近,但它使用的是“AND”而不是“OR”。

于 2013-03-04T18:11:15.707 回答
0

也许你找这个

   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 ;

演示在这里

于 2013-03-04T18:23:30.903 回答