改进MySQL查询性能

时间:2012-12-15 18:16:39

标签: mysql performance select group-by

我有这个查询在两个表companyquestion上运行得很好。两个表都按以下方式构建:

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秒,我仍需要改进它。

由于

1 个答案:

答案 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