我有一个包含产品和标签列的多对多表。如何查询“向我提供映射中只有其中一个标签的产品列表”?
输入:'2,3,4'(这对应于Mappings表中的tagid列)
预期输出:3,4,5(这对应于productid列。产品3,4,5的标签是'2,3,4'的子集(或适当的子集)。
-- Table: Product
+---------+-----------+
| productid | name |
+---------+-----------+
| 1 | HTC |
| 2 | Nokia |
| 3 | Samsung |
| 4 | Motorolla |
| 5 | Apple |
+---------+-----------+
-- Table: Mappings
+------+-----------+
| tagid| productid |
+------+-----------+
| 1 | 1 |
| 1 | 2 |
| 2 | 1 |
| 2 | 3 |
| 3 | 1 |
| 3 | 4 |
| 4 | 5 |
+------+-----------+
-- Table: Tags
+------+-------+
| tagid | name |
+------+-------+
| 1 | blue |
| 2 | black |
| 3 | pink |
| 4 | gold |
+------+-------+
编辑:
预期输出的说明: 输入tagIds - {2,3,4}。 对于tagId 2,在映射表中我们映射了productIds {1,3}。 tagId 3具有映射{1,4},tagId 4具有映射{5}。所以productIds的组合列表是{1,3,4,5} 但是现在productId 1有一个与之关联的tagId 1,它不在tagIds的输入列表中。所以最终输出应该是{3,4,5}。希望这可以解决问题。
答案 0 :(得分:0)
有点像?:
select products.productid, products.name
from products inner join mappings on products.productid = mappings.productid
where mappings.tagid in (2,3,4) -- 2,3,4 is your input
group by products.productid , products.name
having count(*) = 1
编辑:
select products.productid, product.name
from products
where not exists
(
select * from mappings
where products.productid = mappings.productid and not mappings.tagid in (2,3,4)
)
答案 1 :(得分:0)
这有用吗?它适用于MS-SQL。我目前没有运行mysql数据库实例。
select * from products
where (select count(*) from mappings
where products.productid=mappings.productid
AND mappings.tagid in (2,3,4)) = 1
如果添加GROUP BY子句,@ Florian的解决方案也会起作用:
SELECT products.productid,products.productname,count(*)
FROM products
INNER JOIN mappings on products.productid = mappings.productid
AND mappings.tagid in (2,3,4)
GROUP BY products.productid,products.productname
HAVING count(*)=1