我想添加后搜索过滤到电子商务搜索功能。目前的数据是这样的:
产品(带品牌标识)
品牌(产品表中BrandID的外键)
ProductDietType(产品和饮食类型的连接表)
饮食类型(各种产品饮食类型)
生产部门(产品与部门交接表)
部门
我想添加后搜索过滤器,用户可以选择多个品牌,部门,饮食类型,以缩小结果集。
我能想到的就是这样编码:
如果(无)……
如果(品牌)……
如果(部门)……
如果(饮食类型)……
如果(品牌和部门)……
如果(品牌和饮食类型)……
如果(部门和饮食类型)……
如果(品牌和部门以及饮食类型)……
我知道这是错的。因为它的可扩展性不强:每次添加新的过滤器时,代码分支的数量就会增加一倍。
如果我想添加另一个过滤器,比如说,原产国,我可以相对轻松地完成这项工作。
我用C语言编写代码,并使用SQL Server 2008。
非常感谢您的帮助。
乔恩

最佳答案

您可以使用通用方法来处理产品属性。所有可能的筛选条件都称为属性(如“department 1”),按属性类型(如“departments”)分组。
这种模式有利有弊。例如:当品牌只是这些属性中的一个时,如何保证一个产品恰好属于一个品牌?这是模型的一个消极方面。最积极的一面是:不管你谈论的是某个产品的品牌、饮食类型、部门还是其他什么,它们同样只是你可以过滤的产品属性。添加更多属性很容易,而无需更改筛选代码。
表属性类型

id | text
1  | 'Brand'
2  | 'Diet type'
3  | 'Department'

Table attribute

id | id_attribute_type | text
1  | 1                 | 'The Salad Makers'
2  | 1                 | 'Gorgeous Food'
3  | 1                 | 'Great Meals'
4  | 2                 | 'No fat'
5  | 2                 | 'Low carb'
6  | 2                 | 'No lactose'
7  | 3                 | 'Department 1'
8  | 4                 | 'Department 2'

Table product_attribute

id_product | id_attribute
1          | 1
1          | 4
1          | 5
1          | 7
2          | 2
2          | 4
2          | 6
2          | 7

Say you select all products with the word green in their title:

select * from products where upper(name) like '%GREEN%';

此外,还需要与选定产品关联的所有筛选器:
select at.id as at_id, at.text as at_text, a.id as a_id, a.text as a_text
from product_attribute pa
join attribute a on a.id = pa.id_attribute
join attribute_type at on at.id = a.id_attribute_type
where pa.id_product in (select id from products where upper(name) like '%GREEN%');

如果“绿色”产品恰好是产品1和2,那么您将得到:
“品牌”(1)
“沙拉制作者”(1)
“美食”(2)
“饮食类型”(2)
“不胖”(4)
“低碳酸盐”(5)
“无乳糖”(6)
“部门”(3)
“部门1”(7)
现在,用户选择brand='沙拉制造商'和'饮食类型'='没有脂肪'或'没有乳糖'。这使得:
select *
from products
where upper(name) like '%GREEN%'
and id in
(
  select id_product
  from product_attribute
  group by id_product
  having sum(case when id_attribute in (1) then 1 end) > 0 criteria for Brand
  and sum(case when id_attribute in (4,6) then 1 end) > 0 -- criteria for Diet type
);

您只需为每个已使用的属性类型(此处为1个品牌和2个饮食类型)添加一个条件行,其中包含所选属性的in子句,就可以创建这样的查询。
这样的模型可以变得更复杂。例如,可能有一些过滤器与或(所有品牌X或Y的产品)相关,而其他过滤器与和(所有甜味和酸味产品)相关。
好吧,你明白了。我不知道你是否觉得这适合你的工作。只是个主意。如前所述,它有优点,但也有缺点。
您还可以决定使用一个混合的概念(例如:像brand这样的主要属性保持实际列,而其他属性则转到attributes表)。

关于database - 如何为搜索后筛选构建数据库架构,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25609057/

10-10 01:50