简体   繁体   中英

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_comment 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM