2016-05-28 78 views
0

我有如下3表數據庫設計:產品taging SQL查詢來獲取其產品3特定的標籤

products 
pid pname pprice 

tags 
tag_id tag_name 

products_tag ==> Unique(pid,tag_id) 
pid tag_id 
65 1 
65 3 
66 2 
88 2 
88 4 
88 3 

我有要求取得具有標籤識別= 2,3和4。因此,所有的PID結果在這種情況下是88(pid)。什麼是這個問題陳述的SQL查詢?

回答

1
select pid 
from products_tag 
where tagid in (2,3,4) 
group by pid 
having count(tagid) = 3 
+1

你不需要'DISTINCT'因爲'獨特的(PID,TAG_ID)' –

0

使用條件COUNT

SELECT PID, COUNT(CASE WHEN tag_id IN (2,3,4) THEN 1 END) as total 
FROM products_tag 
GROUP BY PID 
HAVING COUNT(CASE WHEN tag_id IN (2,3,4) THEN 1 END) = 3