2012-12-15 192 views
2

我有這個查詢運行良好的兩個表companyquestion。這兩個表是結構化的方式如下:提高MySQL查詢性能

company | question 
id  | id 
name  | company_id 
      | sentiment 

SELECT company.id as company_id, company.name, question.sentiment, 
(SELECT count(*) FROM question 
WHERE question.sentiment=0 AND question.company_id=company.id) AS count 
FROM question 
JOIN company ON company.id=question.company_id 
WHERE question.sentiment = 0 GROUP BY company_id ORDER BY count DESC LIMIT 5 

我一直在試圖找出如何才能避免這似乎減緩查詢執行的子查詢重寫這個。 問題表有1000多條記錄。 此外,使用索引已將執行時間從545.037秒減少到180.228秒,但仍需要改進。

感謝

+0

嘗試「解釋」延伸,看到了優化器如何處理它。可能會給你一些關於如何進行的線索。 – ethrbunny

+0

診斷慢查詢需要全表和索引定義,而不僅僅是描述或釋義。也許你的表格定義不好。也許索引沒有正確創建。沒有看到表和索引定義,我們不能說。 –

回答

2
ALTER TABLE question ADD INDEX (sentiment, company_id); 

SELECT c.id as company_id, c.name, q.sentiment, q.count 
FROM company c 
JOIN (
    SELECT company_id, MAX(sentiment) AS sentiment, COUNT(*) AS count 
    FROM question 
    WHERE sentiment = 0 
    GROUP BY company_id 
    ORDER BY NULL 
) AS q ON c.id = q.company_id 
ORDER BY count DESC LIMIT 5 
+0

哇!它已經從180秒下降到0.640秒,我不敢相信。非常感謝 – Lomse