2011-08-01 74 views
1

我開始變得與子查詢熟悉,但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 (...)部分,那麼它立即執行,但是當上述查詢運行時,使用子選擇,需要幾年才能完成。

優化器一個一個地遍歷所有註釋(數百萬),而不是首先運行子查詢並使用它的值?我在這裏錯過了什麼?

+0

子查詢風險誤報,因爲它會返回最高id_comment每個類別 - 如果值無關的類別相匹配,該行仍將被返回。 「forum_comment」或「persondata」表中是否有任何類別列? –

+0

這是AOK,謝謝你的努力。 – Jauzsika

回答

4

嘗試在移動到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; 
+0

謝謝,像一個魅力工作! – Jauzsika

+2

我會使用EXISTS而不是JOIN –

+1

@OMG Ponies:我會使用SQL Server,但MySQL似乎更喜歡JOIN從我目前看到的... – gbn