问题陈述链接
正确代码(董玉章):
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;
1条答案
按热度按时间mgdq6dx11#
通常情况下,首先对子查询进行聚合,然后再进行连接,因此值是正确的,因为每个chalange\u id只有一行对应的chate\u id和hacker id具有正确的总和。如果先将它们连接在一起,则主查询中每个匹配行的值都会求和一次。
表1:
表2:
如果没有子查询就加入(分组前)
因此,这些数字肯定是错的。
会回来的
但是
会回来的
我不知道您的查询中是否存在这种情况,但这是使用子查询的主要区别