簡體   English   中英

MySQL多對多SELECT查詢

[英]MySQL many-to-many SELECT query

我有一個產品表,一個標簽表和一個將它們鏈接在一起的表ProductTags

產品

ID

ProductTags

ProductID
TagID

標簽

ID

我想在ProductTags表中查詢同時具有TagID 1和2的所有ProductIDs 。我該怎么做?

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

這顯然行不通...無法完全理解該怎么做!

任何幫助,不勝感激!

這是一個“組內查詢”查詢,我喜歡使用group byhaving來解決這些問題。 這是一種方法:

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

您需要在這種情況下使用分組依據

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 

嘗試兩次加入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

嘗試這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM