sql语言——select查询操作实验讲解
实验环境
windows10操作,使用mysql 5.5 command line完成实验
实验内容
实验课教材(mysql技术与实验指导)第73页“实验内容与要求”第1题
基于jxgl数据库,使用sql语句表达以下查询
检索年龄大于23岁的男学生的学号和姓名 检索至少选修一门课程的女学生姓名 检索王林不学的课程的课程号 检索至少选修两门课程的学生学号 检索全部学生都选修的课程的课程号和课程名 检索选修了所有3学分的每门课程的学生平均成绩
步骤及过程
首先按以下sql语句创建测试用的jxgl数据库
create database jxgl; use jxgl; create table if not exists student( sno char(7) not null, sname varchar(16), sage smallint check(sage>=16 and sage<=45), ssex char(2) default '男' check(ssex='男' or ssex='女'), sdept char(2), primary key(sno) ) engine=innodb; insert into student values ('2005001', '钱横', 18, '男','cs'), ('2005002', '王林', 19, '女','cs'), ('2005003', '李民', 23, '男','is'), ('2005004', '赵欣然', 16, '女','ma'); create table if not exists course( cno char(2) not null, cname varchar(20), cpno char(2), ccredit smallint, primary key(cno) ) engine=innodb; insert into course values ('1', '数据库系统', '5', 4), ('2', '数学分析', '', 2), ('3', '信息系统导论', '1', 3), ('4', '操作系统原理', '6', 3), ('5', '数据结构', '7', 4), ('6', '数据处理基础', '', 4), ('7', 'c语言', '6', 3); create table if not exists sc( sno char(7) not null, cno char(2) not null, grade smallint, primary key(sno, cno), foreign key(sno) references student(sno), foreign key(cno) references course(cno) ) engine=innodb; insert into sc values ('2005001', '1', 87), ('2005001', '2', 67), ('2005001', '3', 90), ('2005001', '4', 90), ('2005001', '5', 90), ('2005001', '6', 90), ('2005001', '7', 90), ('2005002', '2', 95), ('2005002', '4', 88), ('2005003', '3', 88), ('2005003', '4', 88), ('2005004', '4', 88);
使用sql语句表达以下查询
检索年龄大于23岁的男学生的学号和姓名
select sno, sname from student where sage>23 and ssex='男';
检索至少选修一门课程的女学生姓名
select student.sname from student, sc where student.ssex='女' and student.sno=sc.sno group by student.sno having count(*)>=1;
检索王林不学的课程的课程号
select cno from course where not exists (select * from student, sc where sc.sno=student.sno and sc.cno=course.cno and student.sname='王林');
检索至少选修两门课程的学生学号
select student.sno from student, sc where student.sno=sc.sno group by student.sno having count(*)>=2;
检索全部学生都选修的课程的课程号和课程名
select cno, cname from course where not exists (select * from student where not exists (select * from sc where sno=student.sno and cno=course.cno));
检索选修了所有3学分的每门课程的学生平均成绩
select avg(grade) from course, sc where course.cno=sc.cno and course.ccredit=3;