1

所以我不是最擅长 SQL 我有这个复杂的 MySQL 查询,我迷路了。我不明白的部分是,来自 UNION 以上部分查询的所有结果都乘以 8。如何这可能吗?为什么它们被乘以 8,我该如何阻止它?我还有一些与此非常相似的其他查询,它们都有同样的问题。任何关于为什么会发生这种情况的想法将不胜感激。谢谢!

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
4

1 回答 1

2

对于调试,只运行第一个没有这些GROUP BY东西的查询并查看返回的底层行。

另请注意,您正在使用LEFT JOIN from rageup_partiesto rageup_team_hosts- 使匹配team_hosts条目可选 - 但随后需要在子句team_id中设置为非 NULL 值。WHERE如果您知道数据脏到需要LEFT JOIN,请将这些条件移动到ON每个LEFT JOIN.

于 2012-09-06T01:00:27.537 回答