To subselect or not to subselect?

流过昼夜 提交于 2019-12-11 10:07:16

问题


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?


回答1:


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;


来源:https://stackoverflow.com/questions/6893274/to-subselect-or-not-to-subselect

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!