子查询产生的差异

k4ymrczo  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(313)

问题陈述链接
正确代码(董玉章):

select con.contest_id,
        con.hacker_id, 
        con.name, 
        sum(total_submissions), 
        sum(total_accepted_submissions), 
        sum(total_views), sum(total_unique_views)
from contests con 
join colleges col on con.contest_id = col.contest_id 
join challenges cha on  col.college_id = cha.college_id 
left join
(select challenge_id, sum(total_views) as total_views, sum(total_unique_views) as total_unique_views
from view_stats group by challenge_id) vs on cha.challenge_id = vs.challenge_id 
left join
(select challenge_id, sum(total_submissions) as total_submissions, sum(total_accepted_submissions) as total_accepted_submissions from submission_stats group by challenge_id) ss on cha.challenge_id = ss.challenge_id
    group by con.contest_id, con.hacker_id, con.name
        having sum(total_submissions)!=0 or 
                sum(total_accepted_submissions)!=0 or
                sum(total_views)!=0 or
                sum(total_unique_views)!=0
            order by contest_id;

我修改了代码,但没有子查询,这是不正确的,并且给出了更大的和值。我不明白写子查询有什么不同?一个简单的测试用例示例将非常有用。谢谢!

select con.contest_id,
        con.hacker_id, 
        con.name, 
        sum(total_submissions), 
        sum(total_accepted_submissions), 
        sum(total_views), sum(total_unique_views)
    from contests con 
    join colleges col on con.contest_id = col.contest_id 
    join challenges cha on  col.college_id = cha.college_id 

        left join view_stats vs 
        on cha.challenge_id = vs.challenge_id 
        left join submission_stats ss
        on cha.challenge_id = ss.challenge_id

    group by con.contest_id, con.hacker_id, con.name
    having sum(total_submissions)!=0 or 
    sum(total_accepted_submissions)!=0 or
    sum(total_views)!=0 or
    sum(total_unique_views)!=0
    order by contest_id;
mgdq6dx1

mgdq6dx11#

通常情况下,首先对子查询进行聚合,然后再进行连接,因此值是正确的,因为每个chalange\u id只有一行对应的chate\u id和hacker id具有正确的总和。如果先将它们连接在一起,则主查询中每个匹配行的值都会求和一次。
表1:

id | value1
 a | 1   
 a | 2
 b | 3

表2:

id | value2
 a | 5
 a | 6

如果没有子查询就加入(分组前)

a | 1 | 5
a | 1 | 6
a | 2 | 5
a | 2 | 6

因此,这些数字肯定是错的。

select Table1.id , sum(value1), sum(value2) from
     Table1 join Table2 on Table1.id = Table2.id

会回来的

a | 6 | 22

但是

select Table1.id , sum(value1), max(sum2) from
     Table1 join (select sum(value2) as sum2 from Table2 group by id) t2 on Table1.id = Table2.id

会回来的

a | 3 | 11

我不知道您的查询中是否存在这种情况,但这是使用子查询的主要区别

相关问题