Reputation: 4165
I have this query which runs great on two tables company
and question
. Both tables are structured in the following way:
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
I have been trying to figure out how to rewrite this in order to avoid the subquery which seems to slow the query execution. The question tables have over 1000 records. Also, using indexes have decreased the execution time from 545.037 sec to 180.228 sec, still I need improve this.
Thanks
Upvotes: 2
Views: 111
Reputation: 562270
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
Upvotes: 2