【发布时间】:2023-03-27 10:24:01
【问题描述】:
我有一个包含 3 个表的数据库 - 产品、标签和产品标签。我需要一个查询 返回具有所有指定标签的所有产品。换句话说,不要返回 如果产品没有所有指定的标签。
products
+----+-----+--------+------------------------+
| id | uid | name | description |
+----+-----+--------+------------------------+
| 1 | p1 | ball | something that bounces |
+----+-----+--------+------------------------+
| 2 | p2 | block | for building stuff |
+----+-----+--------+------------------------+
| 3 | p3 | bucket | holds stuff |
+----+-----+--------+------------------------+
| 4 | p4 | shovel | scoops stuff |
+----+-----+--------+------------------------+
tags
+----+-----+--------+
| id | uid | name |
+----+-----+--------+
| 1 | t1 | blue |
+----+-----+--------+
| 2 | t2 | red |
+----+-----+--------+
| 3 | t3 | green |
+----+-----+--------+
| 4 | t4 | yellow |
+----+-----+--------+
| 5 | t5 | orange |
+----+-----+--------+
product_tags
+-------------+---------+
| product_uid | tag_uid |
+-------------+---------+
| p1 | t1 |
+-------------+---------+
| p1 | t2 |
+-------------+---------+
| p2 | t3 |
+-------------+---------+
| p2 | t4 |
+-------------+---------+
| p2 | t5 |
+-------------+---------+
| p3 | t1 |
+-------------+---------+
| p4 | t1 |
+-------------+---------+
| p4 | t5 |
+-------------+---------+
以下是我正在寻找的一些结果示例:
选择红色(t2)的产品:
+-------------+------+
| product_uid | name |
+-------------+------+
| p1 | ball |
+-------------+------+
选择所有红色和蓝色的产品(t2,t1):
+-------------+------+
| product_uid | name |
+-------------+------+
| p1 | ball |
+-------------+------+
选择所有红色、蓝色和黄色(t2、t1、t4)的产品:
+--------------------+
| NO PRODUCTS |
+--------------------+
选择所有蓝色 (t1) 的产品:
+-------------+--------+
| product_uid | name |
+-------------+--------+
| p1 | ball |
+-------------+--------+
| p3 | bucket |
+-------------+--------+
| p4 | shovel |
+-------------+--------+
选择所有蓝色和橙色的产品(t1,t5):
+-------------+--------+
| product_uid | name |
+-------------+--------+
| p4 | shovel |
+-------------+--------+
这里是一个已经设置好的 SQLFiddle 的链接。我尝试了 LEFT JOIN,但它没有得到我想要的东西。
【问题讨论】: