首页 > 解决方案 > 按同一列上的多个值过滤

问题描述

下面是表格和任务本身的简化版本,如果有任何帮助,实际表格来自 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按制造商和属性过滤产品,属性组之间的条件(例如'颜色,尺寸,..')应该是AND,同一组的属性之间的条件(例如'color')应该是OR . 假设我想获得具有制造商(33 或 56)且颜色为“红色或绿色”且尺寸为“xl 或 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

应该返回:

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

标签: sqlattributesopencartconditional-statementswhere

解决方案


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

运算符的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 值已经是“红色”或“绿色”)

由于您需要具有红色或绿色且 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 开始自动递增索引。

自己测试一下


推荐阅读