I'm working with this query to get counts from three different tables, and to group the results by account ID:
SELECT accountId , SUM(ApplicantsCount) as ApplicantsCount, SUM(ApprovedCount) as ApprovedCount, SUM(ScreenedCount) as ScreenedCount
FROM (
SELECT application.accountId, COUNT(*) ApplicantCount, 0 ApprovedCount, 0 ScreenedCount
FROM application
[accountIdCondition]
GROUP BY application.accountId
UNION
SELECT application.accountId, 0, COUNT(*), 0
FROM application
JOIN termsofapproval ON application.accountId = termsofapproval.accountId
JOIN approvaluserjoin ON termsofapproval.id = approvaluserjoin.termsofapprovalId
[accountIdCondition]
GROUP BY application.accountId
UNION
SELECT application.accountId, 0, 0, COUNT(*)
FROM application
JOIN screened
ON application.id = screened.applicationId
[accountIdCondition]
GROUP BY application.accountId
) CountsTable
GROUP BY CountsTable.accountId
However, it runs too slowly, and times out the task handler I'm calling it in. Is there a way I can write this to run faster?