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:
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_commen开发者_如何学Got IN (...)
section, then it executes in an instant, but when the above query runs, with the subselect, it takes ages to complete.
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
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;
精彩评论