简体   繁体   English

MySQL多对多SELECT查询

[英]MySQL many-to-many SELECT query

I have a Product table, a Tags table and a table that links them together, ProductTags . 我有一个产品表,一个标签表和一个将它们链接在一起的表ProductTags

Product 产品

ID

ProductTags 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? 我想在ProductTags表中查询同时具有TagID 1和2的所有ProductIDs 。我该怎么做?

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 . 这是一个“组内查询”查询,我喜欢使用group byhaving来解决这些问题。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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