码迷,mamicode.com
首页 > 数据库 > 详细

【数据库(二)】嵌套子查询

时间:2015-09-08 18:11:12      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:

嵌套子查询

  集合成员资格

  集合的比较

  空关系测试

  重复元组存在性测试

  from子句的子查询

  with子句

【例子】找出在2009年秋季,和2010年春季通识开课的所有课程

select distinct course_id from section

where semester = ‘Fall‘and year=2009 and course_id in

                           (select course_id from section where semester = ‘Spring‘ and year = 2010);

集合的比较

【例子】找出平均工资最高的系

select dept_name

from instructor

group by dept_name

having avg(salary) >= all(select avg(salary)

               from instructor

               group by dept_name)

 

空关系测试

判断一个集合是否为空集

exists 

not exist 

我们还可以使用not exists结构模拟集合包含(即超集)操作,可以将“关系A包含关系B“携程”not exists(B except A)“

B集差A不存在,意思是B是A的子集。

 

找出选修了Biology系开设的所有的课的学生

使用except结构,写该查询

select distinct S.ID, S.name

from student as S

where not exists ((select course_id from course where dept_name = ‘Biology‘) except (select T.course_id from  takes as T where S.ID = T.ID));

 

重复元祖存在性测试

找出所有在2009年最少开设2次的课程(》=2)

select T.course_id from course as T

where not unique (select R.course_id = R.course_id and R.year =2009);

注:unique, not unique 在oracle 8, sql server 7中不支持。

from子句中的子查询

例子,找出平均工资超过42000美元的那些系中的教师的平均工资

select dept_name,avg_salary

from(select dept_name, avg(salary) from instructor group by dept_name) as dept_avg(dept_name, avg_salary)//橙色部分,相当于局部子视图

where avg_salary > 42000;

 

with子句

找出最大预算的系

with max_budget(value) as(select max(budget)from department)--定义临时关系

select budget

from department, max_budget                   ---------------------使用临时关系

where department.budget = max_budget.value;

 

找出工资总额大于平均值的系

with dept_total (dept_name, value) as(select dept_name, sum(salary) from instructor group by dept_name)//每个系的工资总和

dept_total_avg(value)(select avg(value) from dept_total)//所有系的平均工资

select dept_name

from dept_total A, dept_total_avg B

where A.value>=B.value;

 

【数据库(二)】嵌套子查询

标签:

原文地址:http://www.cnblogs.com/dejunwang/p/4792310.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!