So I’m not the best at SQL I have this complicated MySQL query that I’m lost in. The part I don’t understand is, all of the results that come out of the partial query above UNION are multiplied by 8. How is this possible? Why are they being multiplied by 8 and how can I stop it? I also have a few other queries very similar to this one and they all have this same problem. Any ideas on why this could be happening would be greatly appreciated. Thank you!
SELECT best_thrown
FROM(
SELECT CASE WHEN rageup_echelon.party_id IS NULL THEN 0 ELSE SUM(CASE WHEN rageup_echelon.echelon_vote = 1 THEN 5 ELSE 0 END) - SUM(CASE WHEN rageup_echelon.echelon_vote = 0 THEN 3 ELSE 0 END) END AS best_thrown
FROM rageup_parties LEFT JOIN rageup_echelon ON rageup_parties.party_id = rageup_echelon.party_id
LEFT JOIN rageup_team_hosts ON rageup_parties.party_team_id = rageup_team_hosts.team_id
WHERE rageup_team_hosts.team_id = 1 || rageup_team_hosts.team_id = 2 || rageup_team_hosts.team_id = 3
AND rageup_parties.party_status = 'approved'
AND rageup_parties.party_invites = 'public'
AND rageup_team_hosts.user_id = 1
GROUP BY rageup_parties.party_id
UNION
SELECT CASE WHEN rageup_echelon.party_id IS NULL THEN 0 ELSE SUM(CASE WHEN rageup_echelon.echelon_vote = 1 THEN 5 ELSE 0 END) - SUM(CASE WHEN rageup_echelon.echelon_vote = 0 THEN 3 ELSE 0 END) END AS best_thrown
FROM rageup_parties LEFT JOIN rageup_echelon
ON rageup_parties.party_id = rageup_echelon.party_id
WHERE rageup_parties.party_host_id = 1
AND rageup_parties.party_status = 'approved'
AND rageup_parties.party_invites = 'public'
AND rageup_parties.party_team_id = 'user'
GROUP BY rageup_parties.party_id
ORDER BY best_thrown DESC
LIMIT 1
) AS T
For debugging, run just the first query without the
GROUP BYstuff and look at the underlying rows that are returned.Also note that you’re using
LEFT JOIN from rageup_partiestorageup_team_hosts– making matchingteam_hostsentries optional – but then requiringteam_idto be set to non-NULL values in theWHEREclause. If you know the data is dirty enough to require theLEFT JOIN, move those conditions into theONclauses for eachLEFT JOIN.