Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

More efficient way to write this MySQL query

I am trying to speed this query up, and I am afraid it’s impossible given the large amount of data. But I decided I’ll throw it out there and see if anyone has any suggestions. I have two very simple tables:

contractorList

id contractor
1 John’s Roofing
2 Mark’s Roofing

form_submissions

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

id contractor_id submission
1 1
2 2
3 1
4 4
5 1
6 5

…ETC

I am trying to get JUST the contractor name, id and count the number of submissions. IE

SELECT a.id, a.contractor, count(b.contractor_id) AS submission_count
   FROM `contractorList` a
   LEFT JOIN contractor_form_submissions b
      ON b.contractor_id = a.id
   GROUP BY a.id
   ORDER BY a.contractor

The issue is that, I have about 1200 contractors .. Run by itself is lightning quick. But when I LEFT JOIN and count() their submissions (which can be in the thousands per contractor) the query grinds .. Like minutes, not seconds grinds. Is there a more efficient SQL only route to obtain the count without the query taking forever?

NOTE
that contractorList.id AND form_submissions.id are both PK and indexed

>Solution :

It may be better to do the aggregation before joining, as this creates a smaller intermediate table.

SELECT a.id, a.contractor, IFNULL(b.submission_count, 0) AS submission_count
FROM contractorList AS a
LEFT JOIN (
    SELECT contractor_id, COUNT(*) AS submission_count
    FROM contractor_form_submissions
    GROUP BY contractor_id
) AS b ON a.id = b.contractor_id
ORDER BY a.contractor
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading