了解 EXPLAIN 创建列索引基于

Understanding EXPLAIN to create column index based on

我有这个 update 查询:

explain UPDATE
qanda AS ans1
JOIN qanda AS ans2 ON ans2.related = ans1.related
JOIN qanda AS ques ON ans2.related = ques.id
SET ans1.acceptedanswer = IF( ans1.id <> 3, 0, IFNULL( ans1.acceptedanswer, 0 ) ^ b'1' ),
ans1.aadate = IF( ans1.id <> 3, ans1.aadate, 4353)
WHERE ques.author_id = 29
AND ans2.id = 3
AND ans2.author_id = 31 
AND (ques.amount IS NULL or ans1.acceptedanswer IS NULL)

这是其 EXPLAIN 的结果:

+------+-------------+-------+-------+---------------------------+---------+---------+-------+------+-------------+
| id   | select_type | table | type  |       possible_keys       |   key   | key_len | ref   | rows | Extra       |
+------+-------------+-------+-------+---------------------------+---------+---------+-------+------+-------------+
|    1 | SIMPLE      | ans2  | const | PRIMARY,author_id,related | PRIMARY | 4       | const | 1    | NULL        |
|    2 | SIMPLE      | ques  | const | PRIMARY,author_id         | PRIMARY | 4       | const | 1    | NULL        |
|    3 | SIMPLE      | ans1  | ALL   | related                   | NULL    | NULL    | NULL  | 4    | Using where |
+------+-------------+-------+-------+---------------------------+---------+---------+-------+------+-------------+

需要注意的是我的table只包含4行数据。

那么我的结构好吗?或者我应该在这样的列上创建这样的索引吗?

您在同一个问题中同时有多个问题和多个答案table?这好像是'wrong'。建议 1 个 table 用于问题,1 个 table 用于回答。

SHOW CREATE TABLE 会有帮助。

认为 "composite" 索引...

INDEX(author_id, id)(按此顺序)可能会有用。

我怀疑你的 JOINans1 是不正确的(在业务逻辑意义上,而不是在 SQL 意义上);检查一下。