ITPub博客

首页 > 数据库 > Oracle > sql之20高级查询

sql之20高级查询

原创 Oracle 作者:wmlm 时间:2007-04-10 18:04:38 0 删除 编辑
Advanced Subqueries[@more@]

sql之20高级查询
Advanced Subqueries
--'嵌套子查询与关联子查询的区别'
Nested Subquery Execution
:) The inner query executes first and finds a value.
:) The outer query executes once, using the value from the inner query.
Correlated Subquery Execution
:) Get a candidate row (fetched by the outer query).
:) Execute the inner query using the value of the candidate row.
:) Use the values resulting from the inner query to qualify or disqualify the candidate.
:) Repeat until no candidate row remains.
--'关联子查询的特点:The subquery references a column from a table in the parent query.'

--example1: Find all employees who earn more than the average salary in their department.
SQL> select last_name,salary,department_id
2 from employees outer
3 where salary> (select avg(salary)
4 from employees
5 where department_id=outer.department_id);

LAST_NAME SALARY DEPARTMENT_ID
---------- ---------- -------------
King 24000 90
Lorentz 42000 60
Mourgos 5800 50
Zlotkey 10500 80
Abel 11000 80
Hartstein 13000 20
Higgins 12000 110

另外一种解决方案:
SQL> select a.last_name,a.salary,a.department_id,b.salavg
2 from employees a,(select department_id,avg(salary) salavg
3 from employees
4 group by department_id) b
5 where a.department_id=b.department_id
6 and a.salary>b.salavg;

--example2: Display details of those employees who have switched jobs at least twice.
SQL> select e.employee_id,e.last_name,e.job_id
2 from employees e
3 where 2<= (select count(*) from job_history where employee_id=e.employee_id);

EMPLOYEE_ID LAST_NAME JOB_ID
----------- ---------- ----------
101 Kochhar AD_VP
176 Taylor SA_REP
200 Whalen AD_ASST

--example3:Find employees who have at least one person reporting to them.
SQL> select employee_id,last_name,job_id,department_id
2 from employees outer
3 where exists (select 'x'
4 from employees
5 where manager_id=outer.employee_id);

EMPLOYEE_ID LAST_NAME JOB_ID DEPARTMENT_ID
----------- ---------- ---------- -------------
100 King AD_PRES 90
101 Kochhar AD_VP 90
102 De Haan AD_VP 90
103 Hunold IT_PROG 60
124 Mourgos ST_MAN 50
149 Zlotkey SA_MAN 80
201 Hartstein MK_MAN 20
205 Higgins AC_MGR 110
-- 与上面等价的但是却低效的SQL语句
SELECT employee_id,last_name,job_id,department_id
FROM employees
WHERE employee_id IN (SELECT manager_id
FROM employees
WHERE manager_id IS NOT NULL);

-- 例4 将部门名称添加到employees表中
ALTER TABLE employees ADD(department_name VARCHAR2(14));
UPDATE employees e
SET department_name =
(SELECT department_name
FROM departments d
WHERE e.department_id = d.department_id);

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/271063/viewspace-909778/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: sql之20再看查询
请登录后发表评论 登录
全部评论

注册时间:2008-04-08

  • 博文量
    398
  • 访问量
    3716775