mysql - 推荐 "to optimize the response time of an SQL query"

标签 mysql ruby-on-rails performance view query-optimization

我想知道优化包含超过 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 的帮助不大。

你有很多选择。

  1. 如果您还没有,请确保您有一个索引,其中 rent_id 是索引中的唯一字段,或者是索引中的第一个字段。例如:

    create index rent_id_idx on rent_lines (rent_id)
    
  2. 可以考虑使用mysql的分区系统,根据rent_id进行分区

  3. 您可以创建一个具有较低基数的索引,方法如下:

    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/

相关文章:

php - 如何根据时区设置WP Cron作业时间戳?

MySQL查询嵌套选择问题

ruby-on-rails - Ruby on Rails - 无法加载 postgres 适配器

从 R 函数返回列表与环境

c++ - 按概率排序 if...else if 语句有什么影响?

c++ - 我应该如何从循环中跳出?

MySQL 按月、年计数,如果没有则显示 0

mysql - 如何在 select 子句中使用的子查询选择中选择多个列值

ruby-on-rails - Rails 如何决定使用 PUT 或 POST 方法渲染表单?

ruby-on-rails - has_one :through polymorphic - is it possible?