我有一张餐馆的MySQL表,如下所示:
CREATE TABLE `restaurants` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(32) NOT NULL,
`description` varchar(512) NOT NULL,
`tags` varchar(512) DEFAULT NULL,
`type` enum('A','D','E','L','Q','R','P','T','Z') NOT NULL,
`popularity` int(11) DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `uc_type_name` (`type`,`name`),
KEY `name_idx` (`name`),
KEY `type_popularity_idx` (`type`,`popularity`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
以下是有关该表的一些状态信息:
Name: restaurants
Engine: MyISAM
Version: 10
Row_format: Dynamic
Rows: 72999
Avg_row_length: 84
Data_length: 6204488
Max_data_length: 281474976710655
Index_length: 5280768
Data_free: 0
Auto_increment: 75634
Collation: utf8_general_ci
Checksum: NULL
Create_options:
Comment:
我正在尝试构建一个查询,返回与给定餐馆类型的给定字词匹配的6家最受欢迎的餐厅:
SELECT `id`, `name`, `type`, `description` FROM `restaurants`
WHERE `type` = 'A'
AND (`name` LIKE '%some restaurant%'
OR `description` LIKE '%some restaurant%'
OR `tags` LIKE '%some restaurant%')
ORDER BY `popularity` DESC
LIMIT 6
其中一家餐厅类型A包含61,500家餐厅。此外,这些A类餐厅通常具有相对较长的描述和名称。因此,当没有查找类型A的结果时,查询需要0.8-0.9秒。然而,当有结果时,它们的运行速度可达0.1秒。
如何加快此查询的效果?
答案 0 :(得分:1)
您可以尝试使用fulltext index:
ALTER TABLE `restaurants` ADD FULLTEXT (`name`, `description`, `tags`);
使用MATCH
:
SELECT `id`, `name`, `type`, `description` FROM `restaurants`
WHERE `type` = 'A'
AND MATCH (`name`, `description`, `tags`) AGAINST ('some restaurant')
ORDER BY `popularity` DESC LIMIT 6
另外,运行
EXPLAIN SELECT `id`, `name`, `type`, `description` FROM `restaurants`
WHERE `type` = 'A'
AND MATCH (`name`, `description`, `tags`) AGAINST ('some restaurant')
ORDER BY `popularity` DESC LIMIT 6
检查是否使用了索引。
您可以通过测试了解它是否有帮助。 LIKE和全文搜索的性能可能因环境和表格结构而有很大差异......至少它不会搜索整个表格。