MySQL查询结果很困惑

时间:2012-09-06 00:49:06

标签: mysql

所以我不是最好的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

1 个答案:

答案 0 :(得分:2)

对于调试,只运行没有GROUP BY内容的第一个查询,并查看返回的基础行。

另请注意,您正在使用LEFT JOIN from rageup_partiesrageup_team_hosts - 使匹配的team_hosts条目可选 - 但随后要求team_id设置为非NULL值WHERE条款。如果您知道数据非常脏,需要LEFT JOIN,请将这些条件移到ONLEFT JOIN子句中。