我有以下查询
SELECT DISTINCT table_a.id FROM table_a
INNER JOIN table_b ON table_a.id = table_b.profile_id
WHERE table_b.role_id IN (1,2,3,4,5,6)
我在表_b:上有一个索引
CREATE INDEX test_index ON table_b (role_id, profile_id)
但EXPLAIN让我对table_b "使用临时">
Using where; Using index; Using temporary
我应该创建什么索引来克服这个问题?
更新:解释输出
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
| 1 | SIMPLE | table_b | range | table_b_e1c74d82,test_index | test_index | 5 | NULL | 12860 | Using where; Using index; Using temporary |
| 1 | SIMPLE | table_a | eq_ref | PRIMARY | PRIMARY | 4 | table_b.profile_id | 1 | Using index |
table_b_e1c74d82
索引是(profile_id, production_id, role_id)
索引。
我认为您需要以下索引:
role_id in table_b
profile_id in table_b
id in table_a
MySQL将在查询上运行其优化器,并将为该作业选择最佳优化器。
使用temporary只是意味着要解决查询,MySQL需要创建一个临时表来保存结果。如果查询包含以不同方式列出列的JOIN
、GROUP BY
和ORDER BY
子句,则通常会发生这种情况。