sql之20高级查询

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博客 ” ,链接:http://blog.itpub.net/271063/viewspace-909778/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/271063/viewspace-909778/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值