3

我有一个 10M 行的表product,其中包含诸如 etc 之类的字段color (int), price (float), weight (float), unitprice (int),......现在来自 Web 的用户会动态生成查询,以随机条件(颜色是这里必须有的)和排序方式从该表中查找数据,例如

select * from product where color=1 and price >5 and price <220 and .... order by unitprice limit 75, 25;

select count(*) from product where color=3 and weight <500 and price <30 ... ;

如何在 MySQL 中为具有大约 10 个可能的过滤字段(范围、排序......)的表(InnoDB 或 NDB)建立索引?


编辑:据我了解,MySQL 很可能只会为查询选择一个索引,并且只有复合索引的左侧部分有效。显然,索引所有可能的组合不是一个可行的选择,例如(color, price, weight, create_date, unitprice, ....), ( color, weight, price, create_date, unitprice, ....), (color, unitprice, weight, ....).... 并非所有条件都必须存在于所有查询中。

你会做什么来索引这个表?

4

2 回答 2

1

如果您想对任何字段进行快速查找/过滤/排序,则必须在所有字段上放置索引。

如果颜色是必须的(即在每个查询中使用),最好(color, field)为每个field你拥有的复合索引。

如果确实是每个常见查询的一部分,那么将聚集索引放在(color, product_id)上面也可能值得一试。color

于 2010-10-03T07:38:39.347 回答
0

正如 Tomalak 已经回答的那样,您可能应该为所有字段添加索引(以及复合索引,具体取决于您的查询)。但这当然会减慢写入速度。

如果不确定如何使用索引,可以使用explain命令。

于 2010-10-03T09:56:48.127 回答