[英]To subselect or not to subselect?
I start to get familiarized with subselects, but ATM I'm just scratching my head why MySQL kicks himself in the groin with the following: 我开始熟悉子选择,但ATM我只是在摸不着头脑,为什么MySQL在腹股沟中踢自己以下:
SELECT
id_topic,
id_member_comment,
pd.username,
dt_post
FROM forum_comment c
LEFT JOIN persondata pd
ON c.id_member_comment = pd.id_member
WHERE id_comment IN (
SELECT MAX(last_id_comment) AS id_comment
FROM forum_topic
GROUP BY cat_id
);
If I run the query SELECT MAX(last_id_comment) AS id_comment FROM forum_topic GROUP BY cat_id
separately and substitute the resultset into the id_comment IN (...)
section, then it executes in an instant, but when the above query runs, with the subselect, it takes ages to complete. 如果我分别运行查询
SELECT MAX(last_id_comment) AS id_comment FROM forum_topic GROUP BY cat_id
并将结果集替换为id_comment IN (...)
部分,则它会立即执行,但是当上述查询运行时,使用subselect ,需要很长时间才能完成。
The optimizer goes thru all the comments (many millions) one by one, instead of running the subquery first and use its values? 优化器逐个遍历所有注释(数百万),而不是先运行子查询并使用其值? What am I missing here?
我在这里错过了什么?
Try moving the IN to the FROM clause as an inline derived table 尝试将IN作为内联派生表移动到FROM子句
SELECT
id_topic, id_member_comment, pd.username, dt_post
FROM
(
SELECT MAX(last_id_comment) AS id_comment
FROM forum_topic
GROUP BY cat_id
) AS foo
JOIN
forum_comment c ON foo.id_comment = c.id_comment --AND a cat_id join too?
LEFT JOIN
persondata pd ON c.id_member_comment = pd.id_member;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.