2015-04-01 81 views
0

我有一個產品表,標籤表和鏈接在一起的表,ProductTagsMySQL的許多一對多SELECT查詢

產品

ID 

ProductTags

ProductID 
TagID 

標籤

ID 

我想查詢ProductTags表爲所有ProductIDs表都有TagID 1和2.我該怎麼做?

SELECT * 
From ProductTags 
Where TagID = 1 
    AND TagID = 2 

這顯然不會工作...不能完全讓我的頭圓如何做到這一點!

任何幫助非常感謝!

+0

如果您創建[SQLFiddle](http://sqlfiddle.com/),您可能會增加獲得答案的機會。讓人們很容易回答你的問題。 – kkuilla 2015-04-01 13:00:19

回答

1

這是一個「設置中集」查詢和我喜歡用group byhaving解決這些。以下是一種方法:

SELECT ProductId 
FROM ProductTags 
WHERE TagID IN (1, 2) 
GROUP BY ProductId 
HAVING COUNT(DISTINCT TagId) = 2; 
+0

這工作完美。我不知道在哪裏,「很好」!謝謝 – Lee 2015-04-01 12:08:02

0

您需要通過使用組,並具有針對這種情況

select 
p.id 
from product p 
join producttags pt on pt.ProductID = p.id 
join tags t on t.id = pt.tagid 
where pt.tagid in (1,2) 
group by p.id 
having count(*) = 2 
0

嘗試加入ProductTags表的兩倍。

SELECT t3 From ProductTags t1 join ProductTags t2 on t1.productId=t2.productId join Product t3 Where t1.TagID = 1 AND t2.TagID = 2 
0

試試這個:

SELECT * From ProductTags 
Where TagID = 1 OR TagID = 2