数据库SQL语句复习

1,543 阅读3分钟

创建表

creat table course(
 cno char(4primary key not null,
 cname char(40unique,
 cpno char(4),
 credit int,
 foreign key(cpno) references student(sno)
)

修改表

使用 SQL 语句修改 student 表的结构:将系别改为 15 位定长字符串
alter table student alter column sdept char(15)

查询语句

select sname 姓名,2020-sage 出生年份 from student;

查询 course 表前 20%的记录 
select top 20 percent * from course;

统计所有学生的分数总和、平均分、最高分、最低分及总选课人数
select AVG(grade),MAX(grade),MIN(grade),COUNT(*from sc;

查询选修了 c001 号课程、成绩在 80-99 分之间的学生学号及成绩 
select sno,grade from sc where cno='c001' and Grade between 80 and 99;

查询信息管理系和计算机系的学生姓名和性别 
select sname,ssex from student where sdept in('信息管理','计算机');

查询名字的第 2 个字为“小”或“大”的学生姓名
select sname from student where sname like'-[小大]%';

查询学生中年龄最小的学生姓名和年龄。  
select top 1 sname,sage from student order by sage asc;

查询没有考试的学生学号和相应课程号 
select sno,cno from sc where grade is null;

统计每个学生的选课门数
select sno,avg(grade),count(*from sc group by sno;
查询选课门数超过 3 门的学生学号和选课门数 
select sno,avg(grade),count(*from sc group by sno having count(*)>3;

查询考试成绩大于 90 分的学生学号和姓名(
select student sno ,sname from student sno in(select sno where grade>90);

查询没选“c002”号课程的学生姓名和所在的系
select sname,sdept from student where not exists(select * from sc where  sc.sno=student.sno and sno=‘c002’);

插入元素

将一个新生插入 student 表,其学号为 0821105,姓名为陈波,性别为男,年龄为 19 岁, 系别为信息管理系。 
insert into student values('0821150','赵波',‘男’,19,‘信息管理系’);

更新元素

将学号为 0821102 的学生年龄改为 21 岁,系别改为计算机系。 
update student set sage=21,sdept='计算机' where sno=0821102;

删除元素

删除信息管理系所有及格学生的选课记录;
delete from sc where grade>60 and sno inselect sno from student where sdept='信息管理');