要选择还是不进行选择?

时间:2011-08-01 00:33:43

标签: mysql sql subquery

我开始熟悉子选择,但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
);

如果我单独运行查询SELECT MAX(last_id_comment) AS id_comment FROM forum_topic GROUP BY cat_id并将结果集替换为id_comment IN (...)部分,则会立即执行,但是当上述查询运行时,使用子选择,需要很长时间才能完成

优化器逐个遍历所有注释(数百万),而不是先运行子查询并使用其值?我在这里错过了什么?

1 个答案:

答案 0 :(得分:4)

尝试将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;