I’m trying to create a single query containing optional aggregate values from multiple tables and having some difficulty. I’m going to try to simplify my problem to as few fields as possible.
Tables
applications
appid | pageid
contests
id | appid | winnerid
signups
id | contestid | firstname | lastname
referrals
id | signupid
tickets
id | signupid
Purpose of Query
I’m trying to combine the applications and contests tables based on the pageid parameter, join the signups table to get the winner when available, and then a count of all signups, referrals, and tickets or simply a zero value when none is available.
What I’ve got so far
SELECT t1.*, `Winner`.Name AS Winner, IFNULL(`srt`.Signups,0) AS Signups,
IFNULL(`srt`.Referrals,0) AS Referrals,
IFNULL(`srt`.Tickets,0) AS Tickets
FROM applications a, (contests c LEFT JOIN
/* Join signups table to retrieve winner's first/last name */
(SELECT id, contestid, CONCAT(firstname, ' ' , lastname) AS Name
FROM signups) `Winner`
ON c.winnerid = `Winner`.id
AND c.contestid = `Winner`.contestid) LEFT JOIN
/* Join signups, referrals, and tickets to retrieve counts */
(SELECT s.signupid, COUNT(*) AS Signups, Referrals, Tickets
FROM (signups s LEFT JOIN
(SELECT r.signupid, COUNT(r.id) AS Referrals
FROM signups s, referrals r
WHERE s.signupid = r.signupid) `Referrals`
ON s.signupid = `Referrals`.signupid) LEFT JOIN
(SELECT t.signupid, COUNT(t.id) AS Tickets
FROM signups s, tickets t
WHERE s.signupid = t.signupid) `Tickets`
ON s.signupid = `Tickets`.signupid) `srt`
ON signupid = `srt`.signupid
WHERE a.id = c.applicationid
AND a.pageid = @pageid
ORDER BY c.id IN (SELECT id FROM contests WHERE active = 1) desc, c.addeddate desc;
Problem
I’m positive this isn’t the most efficient way to do what I’m trying to do and regardless it doesn’t work. The values for the signups/referrals/tickets simply returns a count for every record in each of the tables. The winner join works fine, and if I limit it to just the signups, that works as well. The signups table is linked to the contests table, and then the referrals and tickets are related directly to the signups table. Any help on this complex query would be greatly appreciated.
Forgive me if I am misunderstanding, and also for my lack of knowledge of differences between MSSQL and mysql, but I would try something like this: