子查询

来源:互联网 发布:图灵学院 java 源码 编辑:程序博客网 时间:2024/04/29 03:03

子查询
一个查询被嵌套在另一个查询中,就是子查询,子查询作用巨大且非常常用。子查询在很多情况下可以代替自连接,子查询的语句语法更清晰
  如:select select_list from table where expr operator (select select_list from table where expr operator);
可以将子查询放在许多的sql子句中,包括:where子句,having子句,from子句,create view语句中,create table语句,update语句,insert语句的into子句和update语句的set子句中。
在语法中:
    operator包括比较条件,例如 >、= 或者 in。注:比较条件分为两个种类,单行运算符(>,=,>=,<,<>,<=)和多行运算符(in , any ,all ).
    子查询通常涉及一个嵌套的select/子select或内select 语句,字查询通常执行一次。并且它的输出被用于完成主或外查询的查询条件。
    如: select Last_name,e.employee_id from emp e where salary> (select salary from emp where last_name = 'aBel');
    使用子查询的原则:
        一个子查询必须放在括号里,将查询放在比较条件的右边,子查询可以使用的比较条件,子查询可以多次执行。
    子查询分类:
        单行子查询:即子查询只返回一行,从内select 语句只返回一行的查询
   如:select Last_name,job_id from emp where job_id=(select job_id from emp where employee_id =141);
       select Last_name,job_id,salary from emp where salary=(select Min(salary) from emp);
       select department_id ,min(salary) from emp group by department_id having min(salary)>(select min(salary) from emp where department_id=50);
       select job_id,avg(salary) from emp group by job_id having avg(salary)=(select min(avg(salary)) from emp group by job_id);

 多行子查询:子查询将返回多行,从内select语句返回多行的查询
     子查询要想返回多行,需要使用多行比较符: in等于列表中的任何成员  any 比较子查询返回的每个值  all 比较子查询返回的全部值
     如:select last_name,salary ,department_id from emp where salary in(select min(salary) from emp group by department_id);
         select employee_id,last_name,job_id,salary from emp where salary <any(select salary from emp where job_id ='it_prog') and job_id<>'it_prog');
  select employee_id,last_name,job_id,salary from emp where salary>all(select salary from employees where job_id ='it_prog') and job_id<>'it_prog';
        多行查询也会出现空值的现象:
           select emp.last_name from emplyess emp where emp.employee_id not in(select mgr.manager_id from employee mgr);
 多列子查询:子查询返回的不至一列,多列子查询的返回行数可以是单行也可以是多行。从内select语句返回多行(单行、多行)的查询。
总结:
     子查询是一个被嵌在另一个sql语句中的select语句,当一个查询基于一个带有未知中间值的查找标准时,子查询是有用的。
        特性:
   能传递一个数据行到包含一个单行运算符的主语句,例如:=,<>,>,>=,<,or <=;
   能传递多行数据到包含一个多行运算符的主语句,例如in,首先被oracle服务器处理,并且由where或having子句使用其结果可以包含组函数。


 

0 0
原创粉丝点击