使用MySQL EXPLAIN优化查询

时间:2014-01-25 19:02:56

标签: mysql database

我有点像一个db菜鸟,并且有一个令人讨厌的查询需要超过30秒才能运行。我正在尝试更多地了解EXPLAIN并优化查询,但我不知所措。这是查询:

SELECT 
    feed.*, users.username, smf_attachments.id_attach AS avatar, 
    games.name AS item_name, games.image, feed.item_id, u2.username AS follow_name
FROM feed
INNER JOIN following ON following.follow_id = feed.user_id AND following.user_id = 1
LEFT JOIN users ON users.id = feed.user_id
LEFT JOIN smf_members ON smf_members.member_name = users.username
LEFT JOIN smf_attachments ON smf_attachments.id_member = smf_members.id_member
LEFT JOIN games ON games.id = feed.item_id
LEFT JOIN users u2 ON u2.id = feed.item_id
ORDER BY feed.timestamp DESC
LIMIT 25

解释结果:

1 个答案:

答案 0 :(得分:0)

您希望在执行计划中避免的结果(解释语句的输出)是“完全扫描”(解释输出的额外字段)。为了避免它,您需要在表上创建正确的索引。

如果您有表扫描,则表示查询引擎按顺序读取表的每一行。相反,通过索引访问,查询引擎可以更直接地访问相关数据。

此处有更多解释:http://dev.mysql.com/doc/refman/5.0/en/using-explain.html