数据库常用语句(学生选课)

创建表/视图语句

一.创建学生表 课程表 选修表

create Table student
(Sno char(9) primary key,
Sname char(20) unique,
Ssex char(2),
Sage smallint,
Sdept char(20)
)

create table course
(Cno char(4) primary key,
Cname char(40),
Cpno char(4),/*前置课程*/
Ccredit smallint,
foreign key (Cpno) references course(Cno),
)

create table sc
(Sno char(9),
 Cno char(4),
 Grade smallint,
 primary key(Sno,Cno),
 foreign key (Sno) references student(Sno),
 foreign key (Cno) references course(Cno),
)

二.创建男学生视图,属性包括学号、姓名、选修课程名和成绩

create view  Male_student as
select student.Sno,Sname,sc.Cno,Grade from student,course,sc 
where student.Sno=sc.Sno and course.Cno=sc.Cno and Ssex='男'

插入语句

向三个表中插入信息 其中课程由于前导课程限制 不能一次插入

insert into student values('201215121','李勇','男',20,'CS')
insert into student values('201215122','刘晨','女',19,'CS')
insert into student values('201215123','王敏','女',18,'MA')
insert into student values('201215124','张立','男',19,'IS')

insert into course values('1','数据库','5',4)
insert into course values('2','数学',null,2)
insert into course values('3','信息系统','1',4)
insert into course values('4','操作系统','6',3)
insert into course values('5','数据结构','7',4)
insert into course values('6','数据处理',null,2)
insert into course values('7','pascal',6,4)

insert into sc values('201215121','1',92)
insert into sc values('201215121','2',85)
insert into sc values('201215121','3',88)
insert into sc values('201215122','2',90)
insert into sc values('201215122','3',80)

查询语句

查询三个表和一个视图

select * from student
select * from course
select * from sc
select * from Male_student

有条件的查询语句

1.查询选修了课程的学生信息
select student.* from student,sc where student.Sno=sc.Sno
2.查询选修了1号课程且成绩在80-90分之间的学生学号和成绩,并将成绩乘以系数0.8输出
select Sno,Grade*0.8 from sc where Cno='1' and Grade>=80 and Grade<=90
3.查询缺少了成绩的学生的学号和课程号
select Sno,Cno from sc where Grade is null
4.查询选修了“数学”的学生的学号的姓名
select student.Sno,Sname from student,sc,course where student.Sno=sc.Sno 
and sc.Cno=course.Cno and course.Cname='数学'
5.查询选修了1号课程的学生学号和成绩,并要求结果按成绩降序排列,如果成绩相同,则按学号升序排列
select Sno,Grade from sc where Cno='1' order by Grade desc
6.统计每个学生有成绩的课程门数、平均成绩。
select AVG(Grade) as avg,COUNT(Cno) as coursenumber from sc where Grade is not null group by Cno

修改语句

将表student 中所有学生的年龄加2岁
将表sc中所有学生的成绩降低10%

update student set Sage=Sage+2;
update sc set Grade=Grade*0.9 where Sno in (select Sno from sc)

删除表/视图/数据语句

drop table 表名/视图名
delete from student where Sno='95004'

其他数据库博客

学生信息表
图书信息表
数据库上机考试

猜你喜欢

转载自blog.csdn.net/qq_43760243/article/details/112220794
今日推荐