sql练习题+答案 联系客服

发布时间 : 星期三 文章sql练习题+答案更新完毕开始阅读09f50a2bc8aedd3383c4bb4cf7ec4afe04a1b1ec

(一) 新建以下几个表

student(学生表): sno sname sex dept birth age 其中约束如下: (1) (2) (3) (4)

学号不能存在相同的 名字为非空

性别的值只能是’男’或’女’

系包括这几个:信息系,计算机科学系,数学系,管理系,中文系,外语系,法学系

(5) (6)

出生日期为日期格式

年龄为数值型,且在0~100之间

create table student( sno smallint constraint a primary key,----设置学生学号为student的主键 sname varchar(10) not null, sex varchar(2) constraint b check(sex in('男','女')),----检查约束——性别的值只能是’男’或’女’ dept varchar(20) constraint c check(dept in('信息系','计算机科学系','数学系','管理系','中文系','外语系','法学系')),----检查约束——系包括这几个:信息系,计算机科学系,数学系,管理系,中文系,外语系,法学系 birth datetime, age smallint constraint d check(age between 0 and 100)----检查约束——年龄为数值型,且在~100之间

)

cs(成绩表): sno cno cj 其中约束如下:

(1)sno和cno分别参照student和course表中的sno,cno的字段 (2)cj(成绩)只能在0~100之间,可以不输入值

create table cs( sno smallint not null references student(sno),----定义成外键 cno smallint not null references course(cno),----定义成外键 cj smallint constraint e check(cj between 0 and 100),----检查约束——cj(成绩)只能在~100之间,可以不输入值 constraint f primary key(sno,cno)----定义学生学号和课程号为sc表的主键 )

course(课程表) cno cname

其约束如下:

(1)课程号(cno)不能有重复的 (2)课程名(cname)非空

create table course( cno smallint not null constraint g primary key,----设置课程号为course的主键 cname varchar(20) not null )

(三)针对学生课程数据库查询 (1) 查询全体学生的学号与姓名。

Select sno,sname from student

(2) 查询全体学生的姓名、学号、所在系,并用别名显示出结果。

Select sname as '姓名',sno as '学号',dept as '所在地' from student

(3) 查询全体学生的详细记录。

select * from student

(4) 查全体学生的姓名及其出生年份。

select sname,birth from student

(5) 查询学校中有哪些系。

select distinct dept from student

(6) 查询选修了课程的学生学号。

select sno from cs where cno is not null

(7) 查询所有年龄在20岁以下的学生姓名及其年龄。

select sname,age from student where age < 20

(8) 查询年龄在20~23岁(包括20岁和23岁)之间的学生的姓名、系别和年龄。

select sname,dept,age from student where age between 20 and 23

(9) 查询年龄不在20~23岁之间的学生姓名、系别和年龄。

select sname,dept,age from student where age<20 or age>23

(10) 查询信息系、数学系和计算机科学系生的姓名和性别。

select sname,sex from student where dept='信息系' or dept='数学系' or dept='计算机科学系'

(11) 查询既不是信息系、数学系,也不是计算机科学系的学生的姓名和性别。

select sname,sex from student where dept!='信息系' and dept!='数学系' and dept!='计算机科学系'

(12) 查询所有姓刘学生的姓名、学号和性别。