2016-08-01 69 views
-1

我的mySql查詢加載速度很慢(超過30秒),我閒逛我可以優化它的任何調整。Mysql查詢優化 - 獲取所有主題的最後一個帖子

查詢應該返回最後一個字符串爲「?」的帖子。的所有線程。

謝謝。

SELECT FeedbackId, ParentFeedbackId, PageId, FeedbackTitle, FeedbackText, FeedbackDate 
FROM ReaderFeedback AS c 
LEFT JOIN (
    SELECT max(FeedbackId) AS MaxFeedbackId 
    FROM ReaderFeedback 
    WHERE ParentFeedbackId IS NOT NULL 
    GROUP BY ParentFeedbackId 
) AS d ON d.MaxFeedbackId = c.FeedbackId 
WHERE ParentFeedbackId IS NOT NULL 
AND FeedbackText LIKE '%?%' 
GROUP BY ParentFeedbackId 
ORDER BY d.MaxFeedbackId DESC LIMIT 50 
+0

代碼優化問題適用於[代碼評論](http://codereview.stackexchange.com)。你可以在那裏發佈。 –

回答

0

首先你的SQL無效。外部分組是無效的。根據SQL第二組不需要。我搬到了2,其中入內SQL,以及極限,不知道下面的更快:

SELECT FeedbackId, ParentFeedbackId, PageId, FeedbackTitle, FeedbackText, FeedbackDate 
FROM ReaderFeedback AS c 
JOIN (
    SELECT max(FeedbackId) AS MaxFeedbackId 
    FROM ReaderFeedback 
    WHERE ParentFeedbackId IS NOT NULL 
    AND FeedbackText LIKE '%?%' 
    GROUP BY ParentFeedbackId 
    ORDER BY 1 DESC LIMIT 50 
) AS d ON d.MaxFeedbackId = c.FeedbackId 

請看看你的表結構,看看是否有任何正常化擊落了一架速度方面的顧慮。

+0

快得多!謝謝。 – Tom

0

之前討論這個問題,我已經格式化你的SQL:

SELECT feedbackid, 
     parentfeedbackid, 
     pageid, 
     feedbacktitle, 
     feedbacktext, 
     feedbackdate 
FROM readerfeedback AS c 
     LEFT JOIN (SELECT Max(feedbackid) AS MaxFeedbackId 
        FROM readerfeedback 
        WHERE parentfeedbackid IS NOT NULL 
        GROUP BY parentfeedbackid) AS d 
       ON d.maxfeedbackid = c.feedbackid 
WHERE parentfeedbackid IS NOT NULL 
     AND feedbacktext LIKE '%?%' 
GROUP BY parentfeedbackid 
ORDER BY d.maxfeedbackid DESC 
LIMIT 50 

因爲在你的SQL低效的查詢條件:

feedbacktext LIKE '%?%' 

這是不是能夠採取受益於指數需要一個完整的掃描,我建議你添加一個新的字段

isQuestion BOOLEAN 

到你的表,然後在插入/更新反饋文本時,在程序中添加邏輯以分配此字段。 最後你可以根據這個字段進行查詢並從索引中受益。