【发布时间】:2011-09-06 17:06:59
【问题描述】:
从下面的表结构中,我希望能够提供基于属性组合的搜索过滤器:
表格:动物属性
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棕色)并且有(毛皮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
------------------------------------
【问题讨论】:
-
拥有一些测试数据和预期的查询输出真的很有帮助,这样我们就可以尝试各种查询,直到得到正确的答案。
标签: mysql sql search filtering