有一个产品表和一个产品标签表。
尝试选择具有所有标签的所有产品。因此,当用户优化搜索时,他们只会获得带有所有标签的产品。
标签
id PID tag
------------------------------
0c212c04_Gold 0c212c04 Gold
0c212c04_500g 0c212c04 500g
0c212c04_Coin 0c212c04 Coin
最初,我尝试了OR
和IN
,但结果返回了所有。即使他们只有一个必需的标记
SELECT DISTINCT p.*
FROM products p
INNER JOIN product_tags pt ON (p.PID = pt.PID)
WHERE pt.tag = 'Gold' OR pt.tag = '10oz' AND p.RRP BETWEEN 0 AND 1000000
SELECT DISTINCT p.*
FROM products p
INNER JOIN product_tags pt ON (p.PID = pt.PID)
WHERE pt.tag IN ('Gold','10oz') AND p.RRP BETWEEN 0 AND 1000000
因此,我尝试了AND
,它带来了 0 个结果。
SELECT DISTINCT p.*
FROM products p
INNER JOIN product_tags pt ON (p.PID = pt.PID)
WHERE pt.tag = 'Gold' AND pt.tag = '10oz' AND p.RRP BETWEEN 0 AND 1000000
如何带回带有多个标签Gold
和10oz
和Coin
的所有产品?
答案 0 :(得分:2)
您可以使用HAVING
子句:
SELECT p.*
FROM products p JOIN
product_tags pt
ON p.PID = pt.PID
WHERE pt.tag IN ('Gold', '10oz') AND
p.RRP BETWEEN 0 AND 1000000
GROUP BY p.PID -- okay assuming PID is unique/primary key
HAVING COUNT(*) = 2;
答案 1 :(得分:1)
这是一个依赖条件聚合的选项,它可以处理任意数量的条件(只需向HAVING
子句添加更多条件):
SELECT p.id
FROM products p
INNER JOIN product_tags pt ON p.PID = pt.PID
WHERE p.rrp BETWEEN 0 AND 1000000
GROUP BY p.id
HAVING MAX(pt.tag = 'GOLD') = 1 AND MAX(pt.tag = '10oz') = 1
注意:如果您需要products
中的更多列,则需要在SELECT
子句的GROUP BY
和中添加它们(这不会因为主键product.id
已经在非聚合列中,所以会影响查询结果。