๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
ORACLE/SQL

[Oracle] Correlated Subquery ์ƒํ˜ธ์—ฐ๊ด€์ฟผ๋ฆฌ :: ๋งˆ์ด์ž๋ชฝ

by ๐ŸŒปโ™š 2020. 3. 21.

Correlated Subquery

Correlated Subquery๋Š” ๋‚ด๋ถ€ Subquery์—์„œ ์™ธ๋ถ€ํ…Œ์ด๋ธ”์˜ ๊ฐ’์„ ์ฐธ์กฐํ•  ๋•Œ ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค. Subquery์™€๋Š” ๋‹ค๋ฅด๊ฒŒ  Inner Query ๋ถ€ํ„ฐ Outer Query ์ˆœ์„œ๋Œ€๋กœ ์‹คํ–‰๋˜๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๋ผ Outer Query์—์„œ ์ฝ์–ด์˜จ ํ–‰์„ ๊ฐ–๊ณ  Inner์ฟผ๋ฆฌ๋ฅผ ์‹คํ–‰ํ•˜๋Š” ๊ฒƒ์„ ๋ฐ˜๋ณตํ•˜์—ฌ ๊ฒฐ๊ณผ๋ฅผ ์ถœ๋ ฅํ•ด์ค๋‹ˆ๋‹ค. Outer Query์™€ Inner Query์—์„œ ๊ฐ™์€ ํ…Œ์ด๋ธ”์„ ์ฐธ์กฐํ•œ๋‹ค๋ฉด Outer Query์˜ ํ…Œ์ด๋ธ”์— Alias๋ฅผ ์‚ฌ์šฉํ•ด์„œ ๊ตฌ๋ถ„ํ•ด์ค๋‹ˆ๋‹ค.

 

 

์˜ˆ์‹œ๋ฌธ์ œ

Oracle HR ๊ณ„์ •  Employees ํ…Œ์ด๋ธ”์„ ์‚ฌ์šฉํ•ด์„œ

์†Œ์†๋œ ๋ถ€์„œ์˜ ํ‰๊ท  ๊ธ‰์—ฌ๋ณด๋‹ค ๋งŽ์€ ๊ธ‰์—ฌ๋ฅผ ๋ฐ›๋Š” ์‚ฌ์›์„ ์ถœ๋ ฅํ•˜์‹œ์˜ค.
1
2
3
4
5
6
7
8
9
10
11
12
13
SELECT
    FIRST_NAME
    ,JOB_ID
    ,DEPARTMENT_ID
    ,SALARY
FROM EMPLOYEES E
WHERE SALARY > (
    SELECT 
        ROUND(AVG(SALARY))
    FROM EMPLOYEES
    WHERE DEPARTMENT_ID = E.DEPARTMENT_ID
)
AND DEPARTMENT_ID < 60;

Nested Subquery๋ฅผ ์‚ฌ์šฉํ•ด์„œ ์ „์ฒด ์‚ฌ์›์˜ ํ‰๊ท  ๊ธ‰์—ฌ๋ฅผ ๊ตฌํ•˜๋Š” ๊ฒƒ์€ ๋ฌธ์ œ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค. ๊ทธ๋Ÿฌ๋‚˜, ๋งŒ์•ฝ ๊ฐ๊ฐ ์‚ฌ์›๋“ค์˜ ์†Œ์†๋˜์–ด ์žˆ๋Š” ๋ถ€์„œ์˜ ํ‰๊ท  ๊ธ‰์—ฌ๋ฅผ ๊ตฌํ•˜๊ธฐ ์œ„ํ•ด์„œ Correlated Subquery๋ฅผ ์‚ฌ์šฉํ–ˆ์Šต๋‹ˆ๋‹ค.

 

1๋‹จ๊ณ„. Subquery ๋‚ด์—์„œ Main Query์˜ ํ…Œ์ด๋ธ”์„ ์ฐธ์กฐํ•˜๋Š” ๊ฒƒ์„ ํ™•์ธํ•˜๊ณ  Main Query์—์„œ์˜ ํ›„๋ณดํ–‰์„ ๋ฐ›์•„ ์กฐ๊ฑด์— ๋ถ€ํ•ฉ๋˜๋Š” ๊ฐ’์„ ์–ป์Šต๋‹ˆ๋‹ค. ์˜ˆ์ œ์—์„œ๋Š” Subquery์—์„œ Main Query์—์„œ์˜ ์ฒซ๋ฒˆ์งธ ํ–‰์„ ๋“ค๊ณ  ์‚ฌ์› ์ •๋ณด์—์„œ ํ•ด๋‹น ๋ถ€์„œ์˜ ํ‰๊ท  ๊ธ‰์—ฌ๋ฅผ ๊ตฌํ•ฉ๋‹ˆ๋‹ค.

 

2๋‹จ๊ณ„. Subquery์—์„œ ์–ป์€ ๋ถ€์„œ์˜ ํ‰๊ท  ๊ธ‰์—ฌ ๊ฐ’๊ณผ Main Query์˜ ์ฒซ๋ฒˆ์งธ ๊ฐ’์„ ๋น„๊ตํ•˜์—ฌ ํ•ด๋‹น ํ–‰์„ ์ถœ๋ ฅ์— ํฌํ•จ์‹œํ‚ฌ์ง€ ์ •ํ•ฉ๋‹ˆ๋‹ค.

 

3๋‹จ๊ณ„. Main Query์˜ ๋‘๋ฒˆ์งธ ํ–‰์œผ๋กœ ๋„˜์–ด๊ฐ€ ์œ„ ๋‹จ๊ณ„๋ฅผ ๋˜‘๊ฐ™์ด ์ง„ํ–‰ํ•˜์—ฌ ๋งˆ์ง€๋ง‰ ํ–‰๊นŒ์ง€ ๋ฐ˜๋ณตํ•ฉ๋‹ˆ๋‹ค.

 

 

๋Œ“๊ธ€