sql练习题及答案 下载本文

内容发布更新时间 : 2024/5/3 9:28:07星期一 下面是文章的全部内容请认真阅读。

(一) 新建以下几个表

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

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

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

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

(5) (6)

出生日期为日期格式

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

createtable student( sno smallintconstraint a primarykey,----设置学生学号为student的主键 sname varchar(10)notnull, sex varchar(2)constraint b check(sex in('男','女')),----检查约束——性别的值只能是’男’或’女’ dept varchar(20)constraint c check(dept in('信息系','计算机科学系','数学系','管理系','中文系','外语系','法学系')),----检查约束——系包括这几个:信息系,计算机科学系,数学系,管理系,中文系,外语系,法学系 birth datetime, age smallintconstraint d check(age between 0

and 100)----检查约束——年龄为数值型,且在~100之间 )

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

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

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

course(课程表)

cno cname 其约束如下:

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

createtable course( cno smallintnotnullconstraint g primarykey,----设置课程号为course的主键 cname varchar(20)notnull )

(三)针对学生课程数据库查询 (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) 查询学校中有哪些系。

selectdistinct dept from student

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

select sno from cs where cno isnotnull

(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) 查询所有姓刘学生的姓名、学号和性别。

select sname,sno,sex from student where sname like('刘%')

(13) 查询学号为2009011的学生的详细情况。(具体的学号值根据表中数据确定)

select*from student where sno=5

(14) 查询姓“欧阳”且全名为三个汉字的学生姓名

select sname from student where sname like('欧阳_')

(15) 查询名字中第2个字为“晨”字的学生的姓名和学号

select sname,sno from student where sname like('_晨')

(16) 查询所有不姓刘的学生姓名。

select sname,sno from student where sname notlike('刘%')

(17) 查询sql课程的课程号和学分。

select cno from course where cname='sql'

(18) 查询以\开头,且倒数第3个字符为 i的课程的详细情况。