我想知道优化包含超过 2.000.000 条记录的表的 SQL 查询响应时间的最佳解决方案是什么
作为解决方案,我想到了创建一个SQL View 的虚拟表(其实我更喜欢mysql在今年创建的行中早早的搜索,因为这个应用的数据是基于季节的。)
有没有更好的解决方案或推荐?
例如搜索租金 12 的所有租金行
之前=> select * from rent_lines 其中 rent_id = 12
现在=> 我创建了一个 View
CREATE VIEW v_rent_lines
AS SELECT rent_id, category_id, customer_id, amount ..
Where rent_lines FROM created_at > = (select starts_on from seasons where current = true)
select * from v_rent_lines Where rent_id = 12
注意事项:
数据库引擎正在使用InnoDB
我添加了索引表(index_rent_lines_on_rent_id、index_rent_lines_on_category_id、index_rent_lines_on_customer_id)
rent有很多rent_lines
最佳答案
在这种情况下, View 实际上没有任何帮助。作为开发人员, View 主要帮助您通过名称引用更复杂的查询,而不必一直重复细节。它们对 mysql 的帮助不大。
你有很多选择。
如果您还没有,请确保您有一个索引,其中 rent_id 是索引中的唯一字段,或者是索引中的第一个字段。例如:
create index rent_id_idx on rent_lines (rent_id)
可以考虑使用mysql的分区系统,根据rent_id进行分区
您可以创建一个具有较低基数的索引,方法如下:
alter table rent_lines add rent_id_bucket smallint unsigned not null after rent_id; update rent_lines set rent_id_bucket = rent_id>>16; alter table rent_lines add key rent_id_bucket_idx(rent_id_bucket);
这会让你做这样的查询:
select * from rent_lines where rent_id_bucket = 16>>16 and rent_id=16
关于mysql - 推荐 "to optimize the response time of an SQL query",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12142832/