mysql - PHP+MySQL的高可用Search实现

标签 mysql sql performance optimization

我正在建立一个销售服装的新网站。其中大部分都是我自己制作的,我想创建一个网站来销售它们。

我想要一个允许用户使用不同条件进行搜索的高级搜索:

  • 颜色
  • 尺寸
  • 形状
  • Material (金属、塑料等...)
  • Fabric 类型
  • 费用
  • 类型(手套、围巾等...)

所以我有以下 shcema:

product:
id int(10) unsigned not null primary key auto_increment
name varchar(200),
price float(5,2),
color_code_1 int(5) default 0,
color_code_2 int(5) default 0,
color_code_3 int(5) default 0,
color_code_4 int(5) default 0,
color_code_5 int(5) default 0,
etc...

我现在遇到的问题是,如果我搜索 1 种颜色(例如红色)并且红色的颜色代码在 color_code_5 中,搜索将不会返回任何结果。因为我的脚本寻找 1 种颜色,所以只寻找 color_code_1。

所以我的问题是,是否有更好的做法:

//4 = red

... WHERE color_code_1 = 4 OR color_code_2 = 4 OR color_code 3 = 4 OR color_code 4 = 4 OR color_code 1 = 5 OR

问题是如果我添加更多颜色,我将不得不更改我的所有查询并且我认为执行起来不是很快?

最好的方法是什么?

最佳答案

一个常见的最佳做法是创建一个包含所有颜色的表(字典表)。然后根据您要通过添加相应的外键建立的关系使用该表。在您的情况下,每种产品都需要多种颜色,因此需要多对多的关系。为此,您需要创建多对多表格并将产品与多种颜色相关联。

product:
id int(10) unsigned not null primary key auto_increment
name varchar(200),
price float(5,2),

color:
id int(10)
name varchar(100) /*e.g. red*/

product_color:
color_id int(10)
product_id int(10)

这个想法是,正如您已经意识到的那样,您可能有多种颜色,以及其他属性,例如制造商。在这种情况下,您创建一个表(字典表)来保存该信息,如果它是一对多关系,则将外键添加到您的产品表中,如果产品有多个制造商,则将外键添加到另一个多对多表中,反之亦然。

关于mysql - PHP+MySQL的高可用Search实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20078540/

相关文章:

mysql - 如何最好地设计具有多个过滤器的 REST API?

MySQL 存储过程或动态 View

PHP为数据库插入设置默认值

php - DataTable 1.10.15 表显示所有结果,而不是在 PHP 中显示 10 行

performance - 具有 O(1) 插入时间和 O(log m) 查找的数据结构?

sql - VBA + SQL Server - 获取最后插入的 ID

php - mysql 连接相同的表和列名

sql - Powershell 脚本中的 ExecuteReader()

ios - 如何有效地分析 Xcode 中的丢帧?

javascript - 为什么在 javascript 中计算斐波那契比在 haskell 中更快?