2012-11-05 38 views
2

我有以下MySQL查詢似乎正在消耗系統的CPU的處理器時間過多。MySQL查詢消耗系統的CPU的處理器時間過長的數量

查詢是想獲得具有在上週的評論最多的新聞:

$timeago = strtotime("-1 week"); 

$query = "SELECT * , 
    news.id, 
    news.title, 
    news.state, 
    news.date, 
    COUNT(comments.module_id) as comments_count, 
    comments.module, 
    comments.state 
    FROM news 
    LEFT OUTER JOIN comments on comments.module_id = news.id AND comments.module = 'news' AND comments.state = '1' 
    WHERE news.state = '2' 
    GROUP BY news.id, news.title, news.date 
    ORDER BY news.date >= $timeago DESC, comments_count DESC limit 6"; 

$result = mysql_query($query) or die (mysql_error()); 
$data = mysql_fetch_assoc($result); 

查詢服務器我剛剛好,它挑選出其中有意見的最高數量的消息最後一週。新聞表中有17,290條記錄。出於這個原因,我試圖找出以對CPU消耗很健康的方式修復查詢。

任何建議將受到歡迎。

解釋計劃說

| id | select_type |表| |鍵入| possible_keys |鍵| key_len | ref |行| Extra

| 1 | SIMPLE |新聞| ref |狀態|狀態| 4 | const | 17282 |在哪裏使用;使用臨時;使用filesort

| 1 | SIMPLE |評論| ref | module_id | module_id | 101 | saidasea_v2.news.id,const,const | 4

+2

請解釋。 –

+1

顯示查詢的解釋計劃和表格中的記錄數量。 –

+1

這裏似乎存在誤解:請參閱[EXPLAIN的簡介](http://dev.mysql.com/doc/refman/5.5/en/using-explain.html),並將EXPLAIN命令的輸出添加到你的問題,沒有這個信息,我們所能做的只是猜測。 – fvu

回答

1

試着改變你的查詢到這一點:

SELECT * , 
news.id, 
news.title, 
news.state, 
news.date, 
COUNT(comments.module_id) as comments_count, 
comments.module, 
comments.state 
FROM news 
LEFT OUTER JOIN comments on comments.module_id = news.id 
WHERE news.state = '2' 
    AND comments.module = 'news' AND comments.state = '1' 
GROUP BY news.id, news.title, news.date 
ORDER BY news.date >= $timeago DESC, comments_count DESC limit 6 

另外,如果你只需要與它的評論新聞,使用inner join代替left outer join

+0

除了將JOIN內容移至WHERE子句之外,您還做了什麼? –

+0

@AlainCollins:建議使用'inner join'而不是'left outer join'。 –

+0

啊,謝謝。我的大腦並沒有看到其他的東西。 –