【问题标题】:What indexes should be created for this MySQL query [closed]应该为此 MySQL 查询创建哪些索引 [关闭]
【发布时间】:2012-03-08 16:09:15
【问题描述】:

如果我有以下查询,可以创建哪些索引来加快查询速度?

SELECT `residentials`.* 
FROM `residentials` 
WHERE 
  (is_active = 1) AND 
  (
    (created_at > '2012-02-20 20:51:56' OR modified > '2012-02-20 20:51:56') AND 
    list_price >= 229000 AND 
    list_price <= 311000 AND 
    square_feet >= '1223' AND 
    square_feet <= '1654' AND 
    property_type IN ('commercial','condo','detached','house','multi','rowtownhouse','semidetached') AND
    (zip LIKE '%19147%')
  )
ORDER BY list_price DESC

仅供参考,这个查询是由 Rails 生成的,所以我无法完全控制它的构造方式。

使用 EXPLAIN 会产生以下结果:

id = 1

select_type = 简单

桌子 = 住宅

类型 = 范围

possible_keys = index_residentials_on_list_price,index_residentials_on_property_style,index_residentials_on_square_feet,index_residentials_on_modified,index_residentials_on_is_active,index_residentials_on_is_active_and_board_id,index_residentials_is_active_board_id_list_price_property_type,index_residentials_on_is_active_and_created_at_and_modified,dates_and_type,dates_type_price,board_price_type_zip,board_price_type_zip_mls P>

key = index_residentials_on_list_price

key_len = 6

ref = NULL

行 = 209272

额外 = 使用位置

【问题讨论】:

  • 一些关于速度的建议(如下所示使用 EXPLAIN 来查看有什么帮助) - 尝试对 > 和 LIKE 的性能也会很重。我会尝试使用和不使用它以及使用/不使用 zip 索引的查询。

标签: mysql sql ruby-on-rails query-optimization database-indexes


【解决方案1】:

你试过了吗:

EXPLAIN SELECT `residentials`.* 
FROM `residentials` 
WHERE 
  (is_active = 1) AND 
  (
    (created_at > '2012-02-20 20:51:56' OR 
     modified > '2012-02-20 20:51:56') AND 
     list_price >= 229000 AND 
     list_price <= 311000 AND 
     square_feet >= '1223' AND 
     square_feet <= '1654' AND 
     property_type IN ('commercial','condo','detached','house','multi','rowtownhouse','semidetached') AND
     (zip LIKE '%19147%')
  )
ORDER BY list_price DESC

【讨论】:

  • +1 是的,这样做,解释(计划)就是为了这个目的而创建的。如果你仍然被卡住,请发布结果。否则你看到的所有其他建议都会在黑暗中被刺穿。
  • 如果有帮助,我已经在上面添加了 EXPLAIN 的结果
【解决方案2】:

对索引非常重要的列的顺序,试试:

is_active, created_at, modified, list_price, square_feet, property_type 

【讨论】:

    猜你喜欢
    • 2017-05-01
    • 1970-01-01
    • 2016-05-17
    • 2012-07-28
    • 1970-01-01
    • 2021-08-31
    • 1970-01-01
    • 1970-01-01
    • 2012-04-07
    相关资源
    最近更新 更多