题解 | #满足条件的用户的试卷完成数和题目练习数#

满足条件的用户的试卷完成数和题目练习数

https://www.nowcoder.com/practice/5c03f761b36046649ee71f05e1ceecbf

#高难度SQL试卷得分平均值大于80并且是7级红名大佬
#2021年试卷总完成次数exam_cnt和题目总练习次数question_cnt
#只保留2021年有试卷完成记录的用户
#试卷完成数升序,题目练习数降序
select er.uid, count(distinct er.exam_id) exam_cnt, count(distinct pr.id) question_cnt
from exam_record er 
left join practice_record pr on er.uid = pr.uid
and year(er.submit_time) = 2021
and year(pr.submit_time) = 2021
where er.uid in(
    select er.uid
    from exam_record er    
    left join examination_info ei on er.exam_id = ei.exam_id
    left join user_info ui on er.uid = ui.uid
    where level = 7 and tag = 'SQL' and difficulty = 'hard'
    group by er.uid
    having avg(score) >= 80 
)
group by er.uid
order by exam_cnt asc, question_cnt desc;


错误代码:
select er.uid, count(distinct er.exam_id) exam_cnt, count(distinct pr.id) question_cnt
from exam_record er 
left join practice_record pr on er.uid = pr.uid
where er.uid in(
    select er.uid
    from exam_record er    
    left join examination_info ei on er.exam_id = ei.exam_id
    left join user_info ui on er.uid = ui.uid
    where level = 7 and tag = 'SQL' and difficulty = 'hard'
    group by er.uid
    having avg(score) >= 80 
)
and year(er.submit_time) = 2021
and year(pr.submit_time) = 2021
group by er.uid
order by exam_cnt asc, question_cnt desc;

原因:
on和where的执行顺序不同。
from->where->group by->having->select->order by->limit
left join 是在from范围类所以 先on条件筛选表,然后两表再做left join。
而对于where来说在left join结果再次筛选。

on条件是在生成临时表时使用的条件,它不管on中的条件是否为真,都会返回左边表中的记录。
where条件是在临时表生成好后,再对临时表进行过滤的条件。这时已经没有left join的含义(必须返回左边表的记录)了,条件不为真的就全部过滤掉。

全部评论

相关推荐

10-29 19:45
吉林大学 Java
从零开始数:自我评价没有必要写,但是看起来你应该是学了csdiy的一些课程,可以在专业技能里面写上自己比较熟悉操作系统和计网,但如果你是找Java的话,把第一个项目换了吧,现在看起来有点四不像。 无论是黑马点评或者说做个轮子项目,刷题和八股也搞起来吧,而且也没必要等到寒假,最近就可以开始找,找到就偷偷实习呗,别被逮到就行了。
点赞 评论 收藏
分享
牛客41406533...:回答他在课上学,一辈子待在学校的老教授用三十年前的祖传PPT一字一句的讲解,使用谭浩强红皮书作为教材在devc++里面敲出a+++++a的瞬间爆出114514个编译错误来学这样才显得专业
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务