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

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

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的含义(必须返回左边表的记录)了,条件不为真的就全部过滤掉。

全部评论

相关推荐

点赞 评论 收藏
分享
湫湫湫不会java:1.在校经历全删了2.。这些荣誉其实也没啥用只能说,要的是好的开发者不是好好学生3.项目五六点就行了,一个亮点一俩行,xxx技术解决,xxx问题带来xxx提升。第一页学历不行,然后啥有价值的信息也没有,到第二页看到项目了,第一个项目九点,第二个项目像凑数的俩点。总体给人又臭又长,一起加油吧兄弟
点赞 评论 收藏
分享
06-10 21:15
门头沟学院 Java
宁阿:好多这种没🧠的公司,他们估计都不知道毕业的人不能给安排实习岗
实习吐槽大会
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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