我有一张桌子:
详情
--------------------------------------------------------
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 distinct PARENT_ID:
查询的预期输出应为
-------------
PARENT_ID
=============
1
-------------
2
-------------
因为只有PARENT_ID 1和2有'Guitar'='4'和'Radio'='2'
答案 0 :(得分:4)
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';
答案 1 :(得分: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'。
答案 2 :(得分: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 ;