按同一列上的多个值过滤

Filter by multiple values on the same column

接下来是表格和任务本身的简化版本,如果它是 任何帮助实际表都来自 Opencart 的数据库,所以我想要什么 要实现的是按制造商和属性筛选商店中的产品。我所需要的只是提示如何在 sql 中实现这一点,不一定是特定于 opencart 的。努力学习 SQL 所以请不要建议使用模块。

表格:

product
-------------------
ID name description manufacturer_id
0  n0   desc0       33
1  n1   desc1       56
2  n2   desc2       68

product_attribute
-------------------
pID ID text
0   12 red 
0   13 xl
1   12 red
1   13 xs
2   13 xxl

SQL按制造商和属性筛选产品,条件介于 属性组(例如 'color, size, ..')应该是 AND,条件介于 同一组的属性(例如 'color')应该是或。说我想得到 制造商 (33 OR 56) AND 颜色 'red OR green' 和尺寸 'xl OR xxl':

的产品
---------------
Manufacurer
    ✓ 33
    ✓ 56
    o 68

Color
    ✓ red
    ✓ green

Size
    ✓ xl
    o xs
    ✓ xxl
---------------

SELECT p.ID
FROM product p
LEFT JOIN product_attribute pa ON (pa.pID = p.ID)
WHERE p.manufacturer_id = 33 OR p.manufacturer_id = 56
AND   pa.text = red OR pa.text = green
AND   pa.text = xl  OR pa.text = xxl

应该return:

result table
--------------
ID
0

逻辑运算与常规数学运算一样具有优先级。

AND 运算符优先于 OR,就像乘法优先于加法一样。

此外,由于您使用的是字符串,请不要忘记使用双引号或单引号。

p.manufacturer_id = 33 OR p.manufacturer_id = 56
AND   pa.text = "red" OR pa.text = "green"
AND   pa.text = "xl"  OR pa.text = "xxl"

将提供与

相同的结果
p.manufacturer_id = 33
OR (p.manufacturer_id = 56 AND pa.text = "red")
OR (pa.text = "green" AND pa.text = "xl")
OR pa.text = "xxl"

我想你的例子中的查询结果是

result table
--------------
ID
0
1
2

我建议您使用括号以确保您的条件得到很好的尊重。

(p.manufacturer_id = 33 OR p.manufacturer_id = 56)
AND (pa.text = "red" OR pa.text = "green")
AND (pa.text = "xl"  OR pa.text = "xxl")

上面的查询将不起作用,因为对于唯一条目,如果 (pa.text = "red" OR pa.text = "green") 为真,则 (pa.text = "xl" OR pa.text = "xxl") 将为假(因为 pa.text 值已经是 "red" 或 "green")

由于您需要具有红色或绿色且尺寸为 xl 或 xxl 的条目,因此您可以搜索具有其中 2 个尺寸的条目 我假设产品不能同时为绿色和红色同时不能有 2 个不同的尺寸

SELECT p.ID
FROM product p
LEFT JOIN product_attribute pa ON (pa.pID = p.ID)
WHERE (p.manufacturer_id = 33 OR p.manufacturer_id = 56)
AND pa.text IN ("red", "green", "xl", "xxl")
GROUP by pa.text
HAVING COUNT(*) = 2

结果

ID
--
1

1 因为我用 MySQL 测试了它,它以 1 开始自动递增索引。

Test it yourself

使用IN:

WHERE p.manufacturer_id IN (33, 56) AND
      pa.text IN ('red', 'green') AND
      pa.size IN ('xl', 'xxl')

您还需要在字符串常量周围加上单引号。

编辑:

根据您的编辑,我认为您想要:

select pa.pid
from product_attribute pa join
     product p
     on p.id = pa.pid and p.manufacturer_id in (33, 56)
where (pa.id = 12 and pa.text in ('red', 'green')) or
      (pa.id = 13 and pa.text in ('xl', 'xxl'))
group by pa.pid
having count(distinct pa.id) = 2  -- both match