多层SQL查询

来源:互联网 发布:js 控制a标签自动跳转 编辑:程序博客网 时间:2024/04/28 04:48
多层SQL查询

 顾名思义,多层的SQL查询的便在于:“在一个SQL语句中可以包含另一个SQL查询语句,形成内部嵌套的查询类型。”

comparison[ANY|ALL|SOME](sqlstatement)
expression[NOT]IN (sqlstatement)
[NOT]EXISTS(sqlstatement)
comparison
将表达式与内层查询的结果比较的操作。
expression
对内层查询的结果作搜索的表达式。
sqlstatement
为Select语句构成的SQL查询,必须用()将该语句括起来。

  例如:

  我们先从订单表格当中,查询出所有的单位,再将产品表格中的单位与的一一对比,查询出所有高于订单表格的单位价格的记录。

  Select * FROM 产品表格

  Where 单位价格>ANY (Select 单位价格 FROM 订单表格 Where 折扣>=.25);

有些书上将内嵌的select语句称为子查询,子查询形成的结果又成为父查询的条件。
子查询可以嵌套多层,子查询操作的数据表可以是父查询不操作的数据表。子查询中不能有order by分组语句。
再例如:
select emp.empno,emp.ename,emp.job,emp.sal from scott.emp where sal>=(select sal from scott.emp where ename=''WARD'');

在这段代码中,子查询select sal from scott.emp where ename=''WARD''的含义是从emp数据表中查询姓名为WARD的员工的薪水,父查询的含义是要找出emp数据表中薪水大于等于WARD的薪水的员工。上面的查询过程等价于两步的执行过程。
(1)执行“select sal from scott.emp where ename=''WARD''”,得出sal=1250;
(2)执行“select emp.empno,emp.ename,emp.job,emp.sal from scott.emp where sal>=1250;”

带in的嵌套查询

select emp.empno,emp.ename,emp.job,emp.sal from scott.emp where sal in (select sal from scott.emp where ename=''WARD'');

上述语句完成的是查询薪水和WARD相等的员工,也可以使用not in来进行查询。

带any的嵌套查询
select emp.empno,emp.ename,emp.job,emp.sal from scott.emp where sal >any(select sal from scott.emp where job=''MANAGER'');

带any的查询过程等价于两步的执行过程。
(1)执行“select sal from scott.emp where job=''MANAGER''”
(2)查询到3个薪水值2975、2850和2450,父查询执行下列语句:
select emp.empno,emp.ename,emp.job,emp.sal from scott.emp where sal >2975 or sal>2850 or sal>2450;

带some的嵌套查询
select emp.empno,emp.ename,emp.job,emp.sal from scott.emp where sal =some(select sal from scott.emp where job=''MANAGER'');

(1)子查询,执行“select sal from scott.emp where job=''MANAGER''”。
(2)父查询执行下列语句。
select emp.empno,emp.ename,emp.job,emp.sal from scott.emp where sal =2975 or sal=2850 or sal=2450;

带【any】的嵌套查询和【some】的嵌套查询功能是一样的。早期的SQL仅仅允许使用【any】,后来的版本为了和英语的【any】相区分,引入了【some】,同时还保留了【any】关键词。

带all的嵌套查询
select emp.empno,emp.ename,emp.job,emp.sal from scott.emp where sal >all(select sal from scott.emp where job=''MANAGER'');

带all的嵌套查询与【some】的步骤相同。
(1)子查询。
(2)父查询执行下列语句。
select emp.empno,emp.ename,emp.job,emp.sal from scott.emp where sal >2975 and sal>2850 and sal>2450;

带exists的嵌套查询
select emp.empno,emp.ename,emp.job,emp.sal from scott.emp,scott.dept where exists (select * from scott.emp where scott.emp.deptno=scott.dept.deptno);

并操作的嵌套查询
并操作就是集合中并集的概念。属于集合A或集合B的元素总和就是并集。
(select deptno from scott.emp) union (select deptno from scott.dept);

交操作的嵌套查询
交操作就是集合中交集的概念。属于集合A且属于集合B的元素总和就是交集。
(select deptno from scott.emp) intersect (select deptno from scott.dept);


差操作的嵌套查询
差操作就是集合中差集的概念。属于集合A且不属于集合B的元素总和就是差集。
select deptno from scott.dept) minus (select deptno from scott.emp;

并、交和差操作的嵌套查询要求属性具有相同的定义,包括类型和取值范围。  
原创粉丝点击