2015-11-20 47 views
0

查詢創建索引的最佳方法我有這個疑問:什麼是下面

select * from `metro_stations` 
where `is_active` = 1 
    and (`title` like '%search%' or `title_en` like '%search%') 

如何建立有效的索引,如果is_active是TINYINT領域,標題是VARCHAR(255)?

並且怎麼樣這個查詢:

select * from `metro_stations` 
where `is_active` = 1 
and (`title` like '%search%' or 
     `title_en` like '%search%' or 
     `description` like '%search%') 

如果說明字段是文本?

+0

''%search%'不是SARGable。想想全文索引 – lad2025

+0

供參考https://en.wikipedia.org/wiki/Sargable。 'LIKE'是SARGable,但只有'%'在末尾'search%''看到這裏的一些示例http://stackoverflow.com/questions/799584/what-makes-a-sql-statement-sargable –

回答

0

對每列使用全文索引。 如果在查詢中使用「或」如果使用使用seperately FTS指數「和」混合FTS指數(在一個索引中使用多個列) Full Text Index

+0

我添加了兩個不同的查詢: EXPLAIN EXTENDED從'metro_stations'中選擇'id',其中'is_active' = 1和('title'如「%мото%」或'title_en'如「%мото% 「) 似乎不使用索引。這怎麼可能 ? –

+0

從metro_stations中選擇id WHERE match(title)against('мото'BOOLEAN MODE) –

+0

OK,它是我的錯誤。謝謝! 性能如何?這個決定比使用沒有任何索引的LIKE'%search%'更好嗎? –

0
FULLTEXT(title, title_en) 

WHERE is_active = 1 
    AND MATCH(title, title_en) AGAINST ("+search" IN BOOLEAN MODE) 

(這應該工作,要麼InnoDB的(5.6+)或MyISAM)

請記住FULLTEXT中「字長」和「停用詞」的限制。