简体   繁体   中英

MySQL many-to-many SELECT query

I have a Product table, a Tags table and a table that links them together, ProductTags .

Product

ID

ProductTags

ProductID
TagID

Tags

ID

I want to query the ProductTags table for all ProductIDs that have both TagID 1 and 2. How would I do this?

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

This obviously won't work... can't quite get my head round how to do it!

Any help much appreciated!

This is a "set-within-sets" query and I like to solve these using group by and having . Here is one method:

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

You need to use group by and having for this case

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

Try This:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM