我使用以下查询来获取最新文章(文章标题+作者姓名+总评论),但需要很长时间才能运行:
SELECT article.id, title, username, count( comment.id ) AS total_comments
FROM article
LEFT JOIN COMMENT ON comment.article_id = article.id
LEFT JOIN user ON article.user_id = user.id
WHERE STATUS = "open"
AND section = "mobiles"
GROUP BY article.id
ORDER BY article.id DESC
LIMIT 0 , 30
解释的输出是:
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE article ALL status NULL NULL NULL 77 Using where; Using temporary; Using filesort
1 SIMPLE comment ref article_id article_id 5 test.article.id 2
1 SIMPLE user eq_ref PRIMARY PRIMARY 4 test.article.user_id 1
如何重新编写查询以避免创建临时表?
存储引擎是MyISAM。以下是带索引的表详细信息:
article
id, title, body, user_id, status, section
primary key: id
indexes: (user_i),(status,section,id)
comment
id, article_id, user_id, body
primary key: id
index:(article_id)
user
id, username
primary key: id
答案 0 :(得分:1)
这个执行计划非常好。你真的无法避免创建和排序临时表:你的查询调用分组和排序的摘要,嗯,一个临时表。如果为mySQL服务器进程提供更多RAM,则可以使用内存表而不是磁盘表。
答案 1 :(得分:1)
使用子查询而不是分组连接会加快流程。
SELECT article.id, title, username,
(
select count(*) from COMMENT
where comment.article_id = article.id
) AS total_comments
FROM article
LEFT JOIN user ON article.user_id = user.id
WHERE STATUS = "open"
AND section = "mobiles"
ORDER BY article.id DESC
LIMIT 0 , 30
根据上一个问题How to make a nested query?
我希望这会有所帮助。