2011-02-02 154 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)。