如何在 MySQL 中为查找表建立索引

发布于 2024-09-26 05:18:55 字数 759 浏览 8 评论 0原文

我有一个 10M 行表 product ,其中包含 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 ... ;

如何索引表(InnoDB 或 NDB))从该表中查找数据,并具有大约 10 个可能的过滤字段(范围、排序) ...) 像这样在 MySQL 中吗?


编辑:根据我的理解,MySQL 很可能只会为查询选择一个索引,并且只有复合索引的左侧部分可以工作。显然,对所有可能的组合建立索引并不是一个可行的选择,例如(color,price,weight,create_date,unitprice,...),(color,weight,price,create_date,unitprice , ....), (颜色、单价、重量, ....) .... 并非所有条件都必须出现在所有查询中。

您将如何对该表建立索引?

I have a 10M-row table product with fields like color (int), price (float), weight (float), unitprice (int), etc ... Now users from Web dynamically generate queries to lookup data from this table with random conditions (color is a must have here) and order-by such as

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 ... ;

How to index a table (InnoDB or NDB) with about 10 possible filtering fields (with range, sorting ...) like this in MySQL?


EDIT: In my understanding MySQL most likely will pick only one index for a query, and only the left hand part of a composite index will work. Obviously indexing all possible combinations is not a feasible option, such as (color, price, weight, create_date, unitprice, ....), (color, weight, price, create_date, unitprice, ....), (color, unitprice, weight, ....) .... Not all conditions are necessarily present in all queries.

What would you do to index this table?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

苦妄 2024-10-03 05:18:55

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

如果颜色是必须的(即在每个查询中使用),那么最好为您拥有的每个字段(color, field)上创建复合索引。

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

If you want quick lookups/filters/sorts on any field, you must put indexes on all of them.

If color ist a must have (i.e. used in every query), it's best to make composite indexes on (color, field) for each field you have.

Putting the clustered index over (color, product_id) might also be worth a try if color really is a part of every common query.

内心激荡 2024-10-03 05:18:55

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

如果您不确定如何使用索引,可以使用 解释一下命令。

As Tomalak already answered, you probably should add indexes for all fields (and composite indexes, depending on your queries). But of course this can slow writes down.

If you're not sure how the indexes will be used, you can use the explain command.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文