当前位置:主页 > 查看内容

sql

发布时间:2021-07-27 00:00| 位朋友查看

简介:姐姐的代码 select a . stno , a . stname , b . cno , max ( grade ) from student a , course b , score c where a . stno c . stno and b . cno c . cno and a . speciality 通信 group by a . stno , a . stname , b . cno 结果 121001 李贤友 102 92 12……

姐姐的代码

select a.stno,a.stname,b.cno,max(grade)
from student a,course b,score c
where a.stno=c.stno and b.cno=c.cno and a.speciality='通信'
group by a.stno,a.stname,b.cno

结果

121001	李贤友  	102	92
121001	李贤友  	203	88
121001	李贤友  	205	91
121001	李贤友  	801	94
121002	周映雪  	102	72
121002	周映雪  	205	65
121002	周映雪  	801	73
121005	刘刚    	102	87
121005	刘刚    	205	85
121005	刘刚    	801	82

可以看到通信的每个人的所有成绩都出来了,你去对对课本的表。

那是因为你对a.stno,b.cno进行分组了,啥叫分组?分组就意味着唯一性,每一条a.stno,b.cno都是唯一的(是score的主键),所以所有的数据都会出来。

思考一下?让你选择每个专业的最高分?而且是指定了一个专业“通信”。

通信专业在student表中对吧,那既然我们想选通信的最高分,是不是student和score表格就要自然连接一下,直接选出来最高分不就可以了?

那显然你看到这题的时候的想法是这样的对吧?

select a.stno,a.stname,b.cno,max(grade)
from student a,course b,score c
where a.stno=c.stno and b.cno=c.cno and a.speciality='通信'

但是你们注意到有一个max(grade)坏了一锅粥,这是聚合函数,聚合函数前面的想出来的字段必须在group by里面才可以,所以这时候根据保错加上了

group by a.stno,a.stname,b.cno

那就回到了最初的讲解。

所以说,这个时候我们是不是就要解决掉这个

max(grade)的问题。

所以就出来了子查询

我们先把max(grade)查询出来,然后把这个查询得到的结果通过数组放起来,那我们在查询的时候是不是就可以直接把这个max(grade)的条件放到where语句了,因为最高分已经知道了,我们当前要判断的就是我选的这个分是不是最高分,那是不是就是in(也就是子查询了),如果我当前选的这个字段的分数在我已经查到的这个数组里面的话是不是就选出来了。

所以

select a.stno,a.stname,b.cno
from student a,course b,score c
where a.stno=c.stno and b.cno=c.cno and a.speciality='通信' and c.grade in(
select max(grade)
from student d,score f
where d.speciality='通信' and d.stno =f.stno
)


先通过

select max(grade)
from student d,score f
where d.speciality='通信' and d.stno =f.stno

查询通信专业的最高分,所以d和f进行连接,选择专业是通信的得到通信专业的最高分,这时候我们知道最高分了,但是需要知道学号姓名,这就是子查询的用处,能够代替max(grade)去掉group by的影响。

在这里插入图片描述

这个时候94已经选出来了

上面的查询语句也就相当于

select a.stno,a.stname,b.cno
from student a,course b,score c
where a.stno=c.stno and b.cno=c.cno and a.speciality='通信' and c.grade in (94)

在这里插入图片描述

这个时候我们是不是解决了group by产生的分组导致的唯一性问题。

然后你看答案上的:

select max(grade)
from student d,score f
where d.stno =f.stno
group by cno

在这里插入图片描述

这个子查询 是不是会把每个科目的最高分都选出来,那么是不是违背了我们要求的专业最高分(只有一个)

那么这时候子查询的结果是不是就是

(92,94,91,95)

那我们进行外面的查询的时候是不是就是这样的

select a.stno,a.stname,b.cno
from student a,course b,score c
where a.stno=c.stno and b.cno=c.cno and a.speciality='通信' and c.grade in (92,94,91,95)

这样出来的不仅不是其他条目也被选出来了

在这里插入图片描述

所以说答案也是有问题的。

所以说正确是:

select a.stno,a.stname,b.cno
from student a,course b,score c
where a.stno=c.stno and b.cno=c.cno and a.speciality='通信' and c.grade in(
select max(grade)
from student d,score f
where d.speciality='通信' and d.stno =f.stno
)

在这里插入图片描述

;原文链接:https://blog.csdn.net/weixin_45822638/article/details/115801208
本站部分内容转载于网络,版权归原作者所有,转载之目的在于传播更多优秀技术内容,如有侵权请联系QQ/微信:153890879删除,谢谢!
上一篇:Java连接数据库 下一篇:没有了

推荐图文


随机推荐