gpt4 book ai didi

MySQL实现基于多个过滤器的搜索

转载 作者:可可西里 更新时间:2023-11-01 08:37:43 25 4
gpt4 key购买 nike

根据下面的表格结构,我希望能够提供基于属性组合的搜索过滤器:

表:动物属性

id      attributeId     animalId
1 455 55
2 999 55
3 685 55
4 999 89
5 455 89
6 333 93
7 685 93
8 999 93
--------------------------------

前端会有复选框,例如

Animal options

Colour
[ ] Black (id 685)
[x] Brown (id 999)

Body Covering
[ ] Fur (id 233)
[ ] Scales (id 333)
[x] Feathers (id 455)

我希望上面的复选框选择所有棕色并且有羽毛的动物。我可以通过以下查询获取此数据:

SELECT animalId
FROM animalAttributes
WHERE attributeId IN (999,455)
GROUP BY animalId
HAVING COUNT(DISTINCT attributeId) = 2;

我遇到的问题是从多个过滤器中选择了多个选项,例如

Animal options

Colour
[x] Black (id 685)
[x] Brown (id 999)

Body Covering
[x] Fur (id 233)
[ ] Scales (id 333)
[x] Feathers (id 455)

我希望上面的复选框选择所有(黑色OR棕色)AND有(毛皮OR羽毛)的动物.我可以通过以下查询获取此数据:

SELECT animalId
FROM animalAttributes
WHERE
attributeId IN (685,233) ||
attributeId IN (685,455) ||
attributeId IN (999,233) ||
attributeId IN (999,455)
GROUP BY animalId
HAVING COUNT(DISTINCT attributeId) = 2;

如果我想添加额外的过滤器,例如“有尾部”、“会飞”、“血型”等,我认为我需要计算所有组合 (cartesian product) 并遵循和上面的图案一样吗?例如5 个过滤器,每个过滤器都选择了 1 个或多个选项

attributeId IN (x,x,x,x,x) ||
attributeId IN (x,x,x,x,x) ||
attributeId IN (x,x,x,x,x) ||
...
HAVING COUNT(DISTINCT attributeId) = 5;

其他表格供引用

表:属性

attributeId    attributeCategoryId    attribute

233 1 Fur
333 1 Scales
455 1 Feathers
685 2 Black
999 2 Brown
-----------------------------------------------

表:attributeCategories

attributeCategoryId    category
1 Body covering
2 Colour
------------------------------------

最佳答案

attributeId IN (685,233) ||
attributeId IN (685,455) ||
attributeId IN (999,233) ||
attributeId IN (999,455)

将与您编写的内容相同: attributeId IN (685,233,455,999,233)

尝试:

SELECT aa.animalId
FROM animalAttributes aa
LEFT JOIN attributes a ON a.attributeId = aa.attributeId
WHERE
(aa.attributeId IN (685,99) AND a.attributeCategoryId=1) AND
(aa.attributeId IN (223,455) AND a.attributeCAtegoryId=2)
GROUP BY animalId

或者换句话说:(黑色或棕色和 isColor)和(毛皮或羽毛和 isBodyCovering)

未测试,但您应该明白了。

关于MySQL实现基于多个过滤器的搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6208708/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com