Oracle之人生何处欢(没得欢)练习题3(多表)
发布日期:2021-05-16 13:53:20 浏览次数:21 分类:精选文章

本文共 2627 字,大约阅读时间需要 8 分钟。

数据库学习指南:SQL Developer 实战

在学习 SQL Developer 时,实践是关键。以下是一些常见的查询练习,帮助您熟悉数据库操作。

表结构

我们创建了以下表结构:

  • 学生表 (student):

    create table student(sno varchar2(10) primary key,
    sname varchar2(20),
    sage number(2),
    ssex varchar2(5));
    • 插入数据:
      insert into student values ('s001','张三',23,'男');
  • 教师表 (teacher):

    create table teacher(tno varchar2(10) primary key,
    tname varchar2(20));
    • 插入数据:
      insert into teacher values ('t001', '刘阳');
  • 课程表 (course):

    create table course(cno varchar2(10),
    cname varchar2(20),
    tno varchar2(20),
    constraint pk_course primary key (cno, tno));
    • 插入数据:
      insert into course values ('c001','J2SE','t002');
  • 选课表 (sc):

    create table sc(sno varchar2(10),
    cno varchar2(10),
    score number(4,2),
    constraint pk_sc primary key (sno, cno));
    • 插入数据:
      insert into sc values ('s001','c001',78.9);

** 常见查询问题解答

  • 查询c001课程比c002课程成绩高的所有学生的学号

    select x.sno from sc x
    join sc y on x.sno = y.sno
    where x.cno = 'c001'
    and y.cno = 'c002'
    and x.score > y.score;
  • 查询平均成绩大于60分的同学的学号和平均成绩

    select sno, avg(score) from sc
    group by sno
    having avg(score) > 60;
  • 查询所有同学的学号、姓名、选课数、总成绩

    select s.sno, s.sname, count(*), sum(score)
    from student s
    join sc on s.sno = sc.sno;
  • 查询姓“刘”的老师的个数

    select count(*) from teacher where tname like '刘%';
  • 查询没学过“谌燕”老师课的同学的学号和姓名

    select sno, sname from student s
    where sno not in (
    select distinct sno from sc
    where cno in (
    select cno from course
    join teacher t on c.tno = t.tno
    where tname = '谌燕'
    )
    );
  • 查询学过c001且c002课程的同学的学号和姓名

    select s.sno, s.sname from (
    select x.sno from sc x
    join sc y on x.sno = y.sno
    where x.cno = 'c001'
    and y.cno = 'c002'
    ) e
    join student s on e.sno = s.sno;
  • 查询学过谌燕老师所教的所有课的同学的学号和姓名

    select s.sno, s.sname from sc
    join course c on sc.cno = c.cno
    join teacher t on c.tno = t.tno
    where t.tname = '谌燕'
    group by s.sno, s.sname
    having count(*) = (select count(*) from teacher t
    join course c on t.tno = c.tno
    where t.tname = '谌燕');
  • 查询c002课程成绩比c001低的所有同学的学号和姓名

    select sno, sname from sc a
    join sc b on a.sno = b.sno
    where a.cno = 'c002'
    and b.cno = 'c001'
    and a.score < b.score;
  • 查询所有课程成绩小于60的同学的学号和姓名

    select sno, sname from student
    where sno in (
    select distinct sno from sc
    where sc.score < 60
    );
  • 查询没有学全所有课的同学的学号和姓名

    select sno, sname from student
    where sno in (
    select sno from sc
    group by sno
    having count(cno) < (
    select count(distinct(cno)) from sc
    )
    );
  • ** 验证与提交答案**

    通过以上练习,您可以逐步掌握 SQL 查询技巧。在实际操作中,建议逐步测试每个查询,确保语法正确并得到预期结果。

    上一篇:当你的docker容器里apt-get update坏掉的时候
    下一篇:Ubuntu18.04安装并配置Hadoop集群

    发表评论

    最新留言

    第一次来,支持一个
    [***.219.124.196]2025年05月11日 05时37分33秒