数据库
首页 > 数据库> > 数据库习题小结(一)

数据库习题小结(一)

作者:互联网

使用大学模式,用SQL写出如下查询

a.找出Comp. Sci. 系开设的且有3个学分的课程名称。

select title

from course

where dept_name = 'Comp. Sci.' and credits=3;

 

 

 

 结果如上

 

b.找出名叫Einstein的教师所教的所有学生的标识,保证结果中没有重复。

  1. with instor_einstein_teaches(course_id, sec_id, semester, year) as  //创建一个临时的表 里面包括了课程id,学期id,学期,年份 (
  2.   select course_id, sec_id, semester, year from instructor natural join teaches where name = 'Einstein' //将 instruction teacher 自然连接 然后找einstein老师
  3.   ),
  4.   takes_einstein_teaches(ID) as (
  5.   select ID from takes natural join instor_einstein_teaches //将上表的ID给筛出来
  6.   )
  7.   select distinct ID, name from student natural join takes_einstein_teaches;

 输出结果为:

 

 

 (不知道这个为啥跑不出来?挺奇怪的)

c.找出教师的最高工资。

 1.select max(salary) from instructor; //这个就不用多说了 需要注意的是 : max()是函数 不要写成salary(max)

2.select salary 嵌套子查询的方法 FROM instructor WHERE salary>=ALL (select salary FROM instructor );

d.找出工资最高的所有教师(可能有不止一位教师具有相同的工资)

select name,ID FROM instructor WHERE salary>=ALL (select salary FROM instructor );

 

 

e.找出2009年秋季开设的每个课程段的选课人数。

 

    1. with candidate_section (course_id,sec_id, semester, year) as (
    2.   select course_id, sec_id, semester, year from section where semester='Fall' and year=2009
    3.   ),
    4.   section_count(course_id, sec_id, semester, year, student_count) as (
    5.   select course_id, sec_id, semester, year, count(distinct ID) as student_num from takes natural join candidate_section // count(distinct id)是核心,可以唯一的计数
    6.   group by course_id, sec_id, semester, year order by student_num
    7.   )
    8.   select max(student_count) from section_count;

标签:数据库,course,semester,sec,year,习题,小结,id,select
来源: https://www.cnblogs.com/Cxiaoyuan/p/14218742.html