【发布时间】:2012-06-27 15:36:58
【问题描述】:
我一直在研究的一个程序使用一个复杂的 MySQL 查询来组合来自多个具有匹配项 ID 的表的信息。但是,由于我添加了您在下面看到的子查询,因此查询的执行时间从不到 1 秒变为超过 3 秒。您对我可以做些什么来优化此查询以使其更快有什么建议吗?我认为拥有一个复杂的查询比拥有 4 或 5 个更小的查询要好,我错了吗?
SELECT uninet_articles.*,
Unix_timestamp(uninet_articles.gmt),
uninet_comments.commentcount,
uninet_comments.lastposter,
Unix_timestamp(uninet_comments.maxgmt)
FROM uninet_articles
RIGHT JOIN (SELECT aid,
(SELECT poster
FROM uninet_comments AS a
WHERE b.aid = a.aid
ORDER BY gmt DESC
LIMIT 1) AS lastposter,
Count(*) AS commentcount,
Max(gmt) AS maxgmt
FROM uninet_comments AS b
GROUP BY aid
ORDER BY maxgmt DESC
LIMIT 10) AS uninet_comments
ON uninet_articles.aid = uninet_comments.aid
LIMIT 10
【问题讨论】:
-
你需要的表上有所有的“索引”吗?
-
作为一个简短的答案,否和是 - 我没有具体的建议,但你认为一个复杂的查询总是比多个小查询更好是不正确的。
标签: mysql performance subquery