应该为此MySQL查询创建哪些索引

时间:2012-03-08 16:09:15

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

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

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 = SIMPLE

table = residentials

type = range

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

key = index_residentials_on_list_price

key_len = 6

ref = NULL

rows = 209272

额外=使用

2 个答案:

答案 0 :(得分:2)

你有没有尝试过:

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 :(得分:0)

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

is_active, created_at, modified, list_price, square_feet, property_type