我有一个包含 40000 行的简单 MySQL 表:
id CHAR(36) (i am using UUIDs as primary keys)
number_from (INT)
number_to (INT)
有 3 个索引:
primary(id)
number_from(number_from)
number_to(number_to)
看起来像下面这样的简单查询需要相当大的时间 时间量(例如 30 秒或更长时间):
SELECT * FROM numbers WHERE (number_from >= 703911711 AND number_to <= 703911800)
我可以做些什么来优化性能?
最佳答案
将索引分开将强制 MySQL 单独扫描它们。如果您同时索引 number_from
和 number_to
,MySQL 可以在单个索引上执行整个 where
子句:
CREATE INDEX number_from_number_to_ind
ON numbers (number_from, number_to)
将 id
添加到索引实际上将允许 MySQL 在不访问表的情况下执行整个查询,但代价是使索引显着变大。您必须进行基准测试,看看这是否真的提高了查询的性能:
CREATE INDEX all_columns_ind
ON numbers (number_from, number_to, id)
关于mysql范围查询性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29797205/