Вы находитесь на странице: 1из 2

Correlated subquery

select empno,ename from emp where deptno in(select deptno from dept where dept.d
eptno=emp.deptno)
when inner subquery has an reference to outer query then this is know as Correla
ted sub-query.
Correlated subquery are used for row-by-row prcessing.Each subquery is executed
once for every row of the outer query.It is one way of reading every row in a t
able and camparing the values in each row againt the realted data.
Eg: select ename,sal,deptno from emp outer where sal > (select avg(sal) from emp
where deptno=outer.deptno);
Each time a row from the outer query is processed,the inner query is evaluated.
Wrirting single-row and multiple-row subqueries
-----------------
How would you figure out which employees have a manager who works for a departme
nt based in the United Kingdom?
select last_name from employees
where manager_id in
(select employee_id from employees where department_id in
(select department_id from departments where location_id in
(select location_id from locations where country_id='UK')));

Row Subqueries
A row subquery is a subquery variant that returns a single row and can thus retu
rn more than one column value. Legal operators for row subquery comparisons are:
= > < >= <= <> != <=>
The expressions (1,2) and ROW(1,2) are sometimes called row constructors.
create table t1 (
id int primary key auto_increment, c1 varchar(256), c2 varchar(256),
c3 varchar(256), c4 varchar(256));
create table t2 (
id int primary key auto_increment, column1 varchar(256), column2 varchar(256),
column3 varchar(256));
insert into t1 (c1,c2,c3,c4) values ('a1','b1','c1','d1');
insert into t1 (c1,c2,c3,c4) values ('a2','b2','c2','d2');
insert into t1 (c1,c2,c3,c4) values ('a3','b3','c3','d3');
insert into t2 (column1,column2,column3) values ('a1','b1','c1');
insert into t2 (column1,column2,column3) values ('x1','x2','x3');
insert into t2 (column1,column2,column3) values ('y1','y2','y3');
select * from t1;
+----+------+------+------+------+
| id | c1 | c2 | c3 | c4 |
+----+------+------+------+------+
| 1 | a1 | b1 | c1 | d1 |
| 2 | a2 | b2 | c2 | d2 |
| 3 | d1 | a1 | b1 | c1 |
+----+------+------+------+------+
select * from t2;
+----+---------+---------+---------+
| id | column1 | column2 | column3 |
+----+---------+---------+---------+
| 1 | a1 | b1 | c1 |
| 2 | x1 | x2 | x3 |
| 3 | y1 | y2 | y3 |
+----+---------+---------+---------+
mysql> select * from t1 where (c2,c3) =
(select column1,column2 from t2 where id=1);
+----+------+------+------+------+
| id | c1 | c2 | c3 | c4 |
+----+------+------+------+------+
| 3 | d1 | a1 | b1 | c1 |
+----+------+------+------+------+
mysql> select * from t1 where row(c2,c3) =
(select column1,column2 from t2 where id=1);
+----+------+------+------+------+
| id | c1 | c2 | c3 | c4 |
+----+------+------+------+------+
| 3 | d1 | a1 | b1 | c1 |
+----+------+------+------+------+