Note that there are some explanatory texts on larger screens.

plurals
  1. POMySQL: Searching same table multiple times with joins
    primarykey
    data
    text
    <p>I am writing a script to do a partial-word search on messages for a user. Each conversation has a mail_id, and each individual message has a msg_id.</p> <p>I have a table, mail_word_index, which contains a row for each word in a message. </p> <pre><code>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 ; </code></pre> <p>I have a query which takes 0.01 seconds to finish</p> <pre><code>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 </code></pre> <p>However, searching one word at a time only takes 0.002 seconds to finish each one, and 0.004 seconds total:</p> <pre><code>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 </code></pre> <p>The inner join seems to slow down the first query. How would I change the first query to make it faster?</p> <p>The EXPLAIN tells me this:</p> <pre><code>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 </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload