public class DataBase {
public static void main() {
}
}
/*
3.8 嵌套子查询
3.8.1 集合成员资格
SQL允许测试元组在关系中的成员资格。连接次in测试元组是否是集合中的成员,集合
是由select子句产生的一组值构成的。
需求:
找出在2009年秋季和2010年春季学习同时开课的所有课程。
方案一:
用union进行连接
方案二:
用in
select distinct course_id
from section
where semester = 'Fail' and year = 2009 and
course_id in (
select course_id
from section
where semester = 'Spring' and year = 2010);
in 和 not in操作符也能用于枚举集合。
select distinct name
from instructor
where name not in ('Mozart','Einstein')
在SQL中测试任意关系的成员资格也是可以的
select count(distinct ID)
from takes
where(course_id, sec_id, semester, year) in
(select course_id, sec_id, semester, year
from takes
where teaches.ID = 10101);
*/
/*
3.8.2 集合的比较
至少比某一个要大,在SQL中用some表示。
比每一个都要大,在SQL中用all表示。
需求:
找出满足下面条件的所有教师的姓名,他们的工资至少比Biology系某一位教师
的工资要高。
select distinct T.name
from instructor as T, instructor as S
where T.salary > S.salary and S.dept_name = 'Biology'
改进后:
select name
from instructor
where salary > some
(select salary
from instructor
where dept_name = 'Biology');
*/
/*
3.8.3 空关系测试
SQL还有一个特性可测试一个子查询的结果中是否存在元组。exists结构在作为参数的子查询
非空时返回true值。
来自外层查询的一个相关名称可以用在where的子查询中。使用了来自外层查询相关名称的子查询
被称作相关子查询。在包含了子查询的查询中,可以在相关名称上应用作用域规则。根据此规则,在
一个子查询中只能使用此子查询本身定义的,或者在包含此子查询的任何查询中定义的相关名称。
——类似与变量的作用域。
*/
/*
3.8.4 重复元组存在性测试
SQL提供一个布尔函数,用于测试在一个子查询的结果中是否存在重复元组。如果作为参数的子查询
结果中没有重复的元组,unique结构将返回true。
*/
/*
3.8.5 from子句中的子查询
SQL允许在from子句中使用子查询,在此采用的主要观点是,任何select-from-where表达式
返回的结果都是关系,因为可以被插入另一个select-from-where中任何关系可以出现的位置
lateral子句,可以让子查询访问外层查询的相关变量。
select name, salary, avg_salary
from instructor as I1, lateral
(select avg(salary) as avg_salary
from instructor2
where I2.dept_name = I1.dept_name);
*/
/*
3.8.6 with子句
with提供定义临时关系的方法,这个定义只对包含with子句的查询有效。
with max_budge (value) as
(select max(budget)
from department)
select budget
from department, max_budget
where department.budget = max_budget.value;
我们也能用from和where子句中嵌套子查询书写上述查询。但是,用嵌套子查询会使得
查询语句晦涩难懂。with子句使查询在逻辑上更加清晰,它还允许在一个查询内的多个
地方使用视图定义。
——MySql好像不支持with语句
*/
/*
3.8.7 标量子查询
SQL允许子查询出现在返回单个值的表达式能够出现的任何地方。只要该子查询只返回包含
单个属性的单个元组,这样的子查询称作标量子查询。
select dept_name,
(select count(*)
from instructor
where department.dept_name = instructor.dept_name)
as num_instructors
from department;
*/