I am trying to run a query on table ‘apst_mailings’ storing the content of each newsletter we send to our subscribers. Each time we attempt to send the email to an individual we insert a row in apst_mailings_accuses reporting the time and state of the sending, and the ID of the newletter. I wanna list the newsletters and count the total sent and successfully sent for each.
SELECT m.id AS code_mailing,
COUNT(a.adh_code) AS num, COUNT(b.adh_code) AS succes
FROM apst_mailings AS m
LEFT OUTER JOIN apst_mailings_accuses AS a
ON a.id_mailing = m.id
LEFT OUTER JOIN apst_mailings_accuses AS b
ON b.id_mailing = m.id
AND b.etat = 'succes'
GROUP BY m.id
And it simply hangs the server forever. I have tried each join in separated queries and it worked without problem:
// Counts the email sent per mailing
SELECT m.id AS code_mailing,
COUNT(a.adh_code) AS num
FROM apst_mailings AS m
LEFT OUTER JOIN apst_mailings_accuses AS a
ON a.id_mailing = m.id
GROUP BY m.id
SELECT m.id AS code_mailing,
COUNT(b.adh_code) AS succes
FROM apst_mailings AS m
LEFT OUTER JOIN apst_mailings_accuses AS b
ON b.id_mailing = m.id
AND b.etat = 'succes'
GROUP BY m.id
I could split my query but the reason why it doesn’t work really bothers me. Can anyone explain please?
Thanks!
You can what you want in a much simpler way by using a single join and using
SUMto perform a conditional count.But the reason why your query doesn’t work is because you’re joining ALL the rows in subquery a with ALL the matching rows in subquery b in a huge cross join. This could generate a huge temporary result set, which is presumably why the query takes forever to terminate. And even if it did terminate, your counts would be completely off – they would be the product of the two counts.
To solve it do the
GROUP BYfirst. ThenJOINthe result of that to your main table.