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


    嵌套子查询

      集合成员资格

      集合的比较

      空关系测试

      重复元组存在性测试

      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;

    晚来一阵风兼雨
  • 相关阅读:
    X oracle move lob 字段到另外的表空间
    X CentOS7使用firewalld打开关闭防火墙与端口
    X ftpd服务常见配置总结(/etc/vsftpd/vsftpd.conf) 【附参数文件】
    P1853 投资的最大效益
    P1466 [USACO2.2]集合 Subset Sums
    小A点菜
    NASA的食物计划
    动态规划入门笔记
    数字三角形 Number Triangles
    P1825 [USACO11OPEN]Corn Maze S
  • 原文地址:https://www.cnblogs.com/dejunwang/p/4792310.html
Copyright © 2020-2023  润新知