2011-02-02 238 views
0

我將jquery自動完成插件添加到我的位置textfield以幫助用戶更好地選擇位置。在構建之前我沒有意識到的是,查詢會非常緩慢。優化mysql查詢

select * from `geoplanet_places` where name LIKE "%San Diego%" AND (place_type = "County" OR place_type = "Town") 

上面的查詢花費了1.18秒。然後我嘗試添加nameplace_type的索引,但這隻會減慢(1.93s)。

有沒有一種方法來優化此查詢或有其他技術來加快查詢。

這geoplanet_places表有437715行(MySQL的)

CREATE TABLE `geoplanet_places` (
    `id` int(11) NOT NULL auto_increment, 
    `woeid` bigint(20) default NULL, 
    `parent_woeid` bigint(20) default NULL, 
    `country_code` varchar(255) collate utf8_unicode_ci default NULL, 
    `name` varchar(255) collate utf8_unicode_ci default NULL, 
    `language` varchar(255) collate utf8_unicode_ci default NULL, 
    `place_type` varchar(255) collate utf8_unicode_ci default NULL, 
    `ancestry` varchar(255) collate utf8_unicode_ci default NULL, 
    `activity_count` int(11) default '0', 
    `activity_count_updated_at` datetime default NULL, 
    `bounding_box` blob, 
    `slug` varchar(255) collate utf8_unicode_ci default NULL, 
    PRIMARY KEY (`id`), 
    UNIQUE KEY `index_geoplanet_places_on_woeid` (`woeid`), 
    KEY `index_geoplanet_places_on_ancestry` (`ancestry`), 
    KEY `index_geoplanet_places_on_parent_woeid` (`parent_woeid`), 
    KEY `index_geoplanet_places_on_slug` (`slug`), 
    KEY `index_geoplanet_places_on_name` (`name`), 
    KEY `index_geoplanet_places_on_place_type` (`place_type`) 
) ENGINE=InnoDB AUTO_INCREMENT=5652569 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; 

EXPLAIN

id 1 
select_type SIMPLE 
table geoplanet_places 
type ALL 
possible_keys index_geoplanet_places_on_place_type 
key NULL 
key_len NULL 
ref NULL 
rows 441273 
Extra Using where 
+0

請發佈`EXPLAIN select * from geoplanet_places的輸出,其中名稱LIKE「%San Diego%」和(place_type =「County」或place_type =「Town」)` – cam 2011-02-02 05:15:42

回答

3

您可以將表格的存儲引擎切換到MyISAM利用全文索引的。

name指數不會幫助你,除非你改變等,以LIKE 'San Diego%'它可以在索引

+0

哇,讓查詢在(21m)中運行!謝謝!! – jspooner 2011-02-02 05:23:07

2

擺脫在哪裏般條款開頭的「%」做前綴搜索,因此它成爲:像「聖地亞哥%」這樣的名字。對於自動完成,這似乎是一個合理的限制(假定用戶開始鍵入正確的字符),這將顯着提高查詢速度,因爲MySql將能夠使用現有索引(index_geoplanet_places_on_name)。