【问题标题】:MySQL: Searching same table multiple times with joinsMySQL:使用连接多次搜索同一个表
【发布时间】:2012-05-23 17:59:31
【问题描述】:

我正在编写一个脚本来对用户的消息进行部分单词搜索。每个对话都有一个 mail_id,每个单独的消息都有一个 msg_id。

我有一个表 mail_word_index,其中包含消息中每个单词的一行。

CREATE TABLE IF NOT EXISTS `mail_word_index` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `sender_id` int(10) unsigned NOT NULL DEFAULT '0',
  `dest_id` int(10) unsigned NOT NULL DEFAULT '0',
  `mail_id` int(10) unsigned NOT NULL DEFAULT '0',
  `msg_id` int(10) unsigned NOT NULL DEFAULT '0',
  `word` varchar(15) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`),
  KEY `dest_id` (`dest_id`,`word`),
  KEY `sender_id` (`sender_id`,`word`),
  KEY `multiple_words` (`mail_id`,`msg_id`,`word`)
) ENGINE=MyISAM ;

我有一个查询需要 0.01 秒才能完成

SELECT DISTINCT w1.mail_id FROM mail_word_index AS w1,
mail_word_index AS w2 
WHERE w1.sender_id=1 
AND w1.word LIKE 'str%' 
AND w1.mail_id=w2.mail_id 
AND w1.msg_id=w2.msg_id 
AND w2.word LIKE 'con%' LIMIT 20

但是,一次搜索一个单词只需要 0.002 秒即可完成每个单词,总共需要 0.004 秒:

SELECT DISTINCT w1.mail_id FROM mail_word_index AS w1 
WHERE w1.sender_id=1 AND w1.word LIKE 'str%' LIMIT 20

SELECT DISTINCT w1.mail_id FROM mail_word_index AS w1 
WHERE w1.sender_id=1 AND w1.word LIKE 'con%' LIMIT 20

内部连接似乎减慢了第一个查询。如何更改第一个查询以使其更快?

解释告诉我这个:

id  select_type table   type    possible_keys   key key_len ref rows    Extra
1   SIMPLE  w1  range   sender_id,multiple_words    sender_id   21  NULL    1   Using where; Using temporary
1   SIMPLE  w2  ref multiple_words  multiple_words  8   game-node4.w1.mail_id,game-node4.w1.msg_id  8   Using where; Using index; Distinct

【问题讨论】:

  • 认真担心6ms??
  • Afaik,您的 multiple_words 已经是该查询的最佳索引。它会更慢,因为 MySQL 必须加入。
  • 随着表越来越大,一次搜索的词越来越多,多连接查询之间的时间差,以及每个单独查询的总时间越来越大
  • @ZPS:要大多少?你能量化吗?
  • 关于“慢”查询,EXPLAIN 告诉你什么?

标签: mysql sql database search


【解决方案1】:

在这种情况下,为 w1 创建索引 multi:

ALTER TABLE `mail_word_index`
ADD INDEX `multi` USING BTREE (`sender_id`, `mail_id`, `msg_id`, `word`) ;

【讨论】:

    猜你喜欢
    • 2015-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-14
    • 2012-04-12
    • 1970-01-01
    • 2011-08-01
    • 1970-01-01
    相关资源
    最近更新 更多