常见的SQL笔试题和面试题(上):经典50题
阅读原文时间:2021年04月25日阅读:1

题目转自:https://zhuanlan.zhihu.com/p/38354000

已知有如下4张表:

学生表:STUDENT(S#,SNAME,SAGE,SSEX)

课程表:COURSE(C#,CNAME,T#)

成绩表:SC(S#,C#,SCORE)

教师表:TEACHER(T#,TNAME)

其中,

1)学生表里的字段含义:

S#代表学号,SNAME代表学生姓名,SAGE代表学生年龄,SSEX代表学生性别

2)课程表里的字段含义:

C#代表课程编号,CNAME代表课程名字,T#代表教师编号,

3)成绩表

S#代表学号,C#代表课程编号,SCORE代表成绩

4)教师表的字段含义:

T#代表教师编号,TNAME代表教师姓名

自己赋值:

student表:

Course表:

Teacher表:

SC表:

由于建表时忘记设置主键,需要增加(sno,cno)一起为主键,方便后期引用,注意,每个字段更新语句后面用逗号分开,否则会报错。

方法一:

alter table sc
change column sno sno int(11) not null,
change column cno cno int(11) not null,
add primary key(sno,cno)

方法二:

alter table sc
modify sno int(11) not null,
modify cno int(11) not null,
add primary key(sno,cno)

1.查询课程编号为“001”的课程比“002”的课程成绩高的所有学生的学号

select x.sno,x.score,y.score from sc x,sc y
where  x.cno=1001 
   and y.cno=1002
   and x.sno=y.sno
   and x.score > y.score

2.查询平均成绩大于60分的学生的学号和平均成绩

select sno,avg(score) from sc
group by sno
having avg(score)>60

3.查询所有学生的学号、姓名、选课数、总成绩

select sc.sno,sname,count(cno),sum(score)
from student join sc
on student.sno=sc.sno
group by sc.sno,sname

4、查询姓“悟”的老师的个数

select count(Tname) from teacher
where Tname like '悟%'

5、查询没学过“悟空”老师课的学生的学号、姓名

(对原始SC表稍作修改,令1,2号学生没有学过悟空的课

delete from sc where sno=1 and cno=1009

delete from sc where sno=2 and cno=1009

select sno,sname from student 
where sno not in(select sno from SC where cno in(select cno from course
where tno in(select tno from teacher
where tname='悟空')))

6、查询学过“悟空”老师所教的所有课的同学的学号、姓名

(对原始表Course,SC稍作修改,让悟空交2门课

insert into course values('1010','Exercise','TS04')

insert into sc values
('8','1010','75'),
('9','1010','92'),
('10','1010','80');

)

7、查询学过编号为“1001”的课程并且也学过编号为“1010”的课程的学生的学号、姓名

8、查询课程编号为“1002”的总成绩

select sum(score) from sc 
where cno='1002'

9、查询所有课程成绩小于60分的学生的学号、姓名

select sno,sname from student
where sno in(select sno from SC where score <60)

10、查询没有学全所有课的学生的学号、姓名

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器