我在尝试优化mysql中的NOT IN子句时:最终得到了以下查询:
SELECT @i:=(SELECT correct_option_word_id FROM sent_question WHERE msisdn='abc');
SELECT * FROM word WHERE @i IS NULL OR word_id NOT IN (@i);
sent_question
表和word
表之间没有关系。而且我无法在correct_option_word_id
上放置索引。
有人能解释一下,这种方法是否能优化查询吗?
更新:如此处所述,NOT IN和LEFT JOIN / IS NULL两种方法几乎同样有效。这就是为什么我不想使用LEFT JOIN / IS NULL方法。
更新2: 原始查询的解释结果:
EXPLAIN SELECT * FROM word WHERE word_id NOT IN (SELECT correct_option_word_id FROM sent_question WHERE msisdn='abc');
+----+--------------------+---------------+------+-------------------------+-------------------------+---------+-------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+--------------------+---------------+------+-------------------------+-------------------------+---------+-------+------+-------------+
| 1 | PRIMARY | word | ALL | NULL | NULL | NULL | NULL | 10 | Using where |
| 2 | DEPENDENT SUBQUERY | sent_question | ref | fk_question_subscriber1 | fk_question_subscriber1 | 48 | const | 1 | Using where |
+----+--------------------+---------------+------+-------------------------+-------------------------+---------+-------+------+-------------+
sent_question
和word
之间有关系吗?最初的查询是什么? - Marcus Adamssent_question
表和word
表之间没有关联。此外,我也无法在correct_option_word_id
上创建索引。 - user517491EXPLAIN
结果。 - Marcus Adams