๐Ÿ’ญ Subquery (๋ถ€์งˆ์˜)

๐Ÿ’ญ Subquery (๋ถ€์งˆ์˜)

์ฃผ๋กœ where ์กฐ๊ฑด์— ์ž‘์šฉํ•˜๋Š” ํ•˜๋‚˜์˜ ์ฟผ๋ฆฌ๋กœ์จ, ๋‚ด๋ถ€์งˆ์˜๋ฅผ ํ†ตํ•ด ์™ธ๋ถ€์˜ ๋ณธ ๋ชฉ์ ์ธ ์ฟผ๋ฆฌ๋ฅผ ํ•ด์„ํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•˜๋Š”๊ฒƒ.

โœ”๏ธ ์›์น™์ ์œผ๋กœ๋Š” ์„œ๋ธŒ์ฟผ๋ฆฌ ๋‚ด์—์„œ order by ์ ˆ์„ ํฌํ•จํ•  ์ˆ˜ ์—†๋‹ค.

โ˜๏ธ ๋‹จ์ผํ–‰ ์„œ๋ธŒ์ฟผ๋ฆฌ

๋ฉ”์ธ ์ฟผ๋ฆฌ๋กœ ์ „๋‹ฌ ๋˜๋Š” ํ–‰์ด ํ•˜๋‚˜์ผ ๊ฒฝ์šฐ๋ฅผ ๋งํ•œ๋‹ค.

โœ”๏ธ ์„œ๋ธŒ์ฟผ๋ฆฌ์—์„œ ๋ฉ”์ธ์ฟผ๋ฆฌ๋กœ์˜ ์ „๋‹ฌ์€ ์ฃผ๋กœ ํ•˜๋‚˜์˜ ์˜คํผ๋ ˆ์ดํ„ฐ๋กœ ์ด๋ฃจ์–ด์ง„๋‹ค.

โ— ์„œ๋ธŒ ์ฟผ๋ฆฌ ์‚ฌ์šฉ์‹œ ์œ ์˜์ 

FROM ์ ˆ์— ์˜ค๋Š” ํ…Œ์ด๋ธ” ์œ„์น˜์— ์„œ๋ธŒ์ฟผ๋ฆฌ๋ฅผ alias์‹œํ‚จ ํ…Œ์ด๋ธ”์„ ์„ ์–ธํ•˜์—ฌ ์‚ฌ์šฉ ํ•˜๋Š” ๋ฐฉ๋ฒ•๋„ ์žˆ์Œ์„ ์œ ์˜ํ•˜์ž.

๐Ÿ“œ ์‹ค์Šต๋ฌธ์ œ 1. ํ˜„์žฌ ์ „์ฒด์‚ฌ์›์˜ ํ‰๊ท  ์—ฐ๋ด‰๋ณด๋‹ค ์ ์€ ๊ธ‰์—ฌ๋ฅผ ๋ฐ›๋Š” ์‚ฌ์›์˜ ์ด๋ฆ„, ๊ธ‰์—ฌ๋ฅผ ๋‚˜ํƒ€๋‚ด์„ธ์š”.

SELECT Concat(a.first_name, ' ', a.last_name) AS NAME,
       b.salary
FROM   employees a,
       salaries b
WHERE  a.emp_no = b.emp_no
       AND b.to_date = '9999-01-01'
       AND b.salary < (SELECT Avg(salary)
                       FROM   salaries
                       WHERE  to_date = '9999-01-01');
SELECT Min(avg_salary)
FROM   (SELECT Round(Avg(a.salary)) AS avg_salary
        FROM   salaries a,
               titles b
        WHERE  a.emp_no = b.emp_no
               AND a.to_date = '9999-01-01'
               AND b.to_date = '9999-01-01'
        GROUP  BY b.title) a;

๐Ÿค˜ ๋‹ค์ค‘ํ–‰ ์„œ๋ธŒ์ฟผ๋ฆฌ

๋ฉ”์ธ์ฟผ๋ฆฌ๋กœ์˜ ์ „๋‹ฌ ๋˜๋Š” ์„œ๋ธŒ์ฟผ๋ฆฌ์˜ ํ–‰์ด ์—ฌ๋Ÿฌ๊ฐœ์ธ ๊ฒฝ์šฐ ๋‹ค์ค‘ํ–‰ ์—ฐ์‚ฐ์ž IN ANY ALL ์„ ์‚ฌ์šฉํ•œ๋‹ค.

๐Ÿ“œ ํ˜„์žฌ 50000 ๋ณด๋‹ค ๋งŽ์€ ๊ธ‰์—ฌ๋ฅผ ๋ฐ›๋Š” ์‚ฌ์›์˜ ์ด๋ฆ„๊ณผ ๊ธ‰์—ฌ๋ฅผ ๊ตฌํ•˜์„ธ์š”

SELECT a.first_name,
       b.salary
FROM   employees a,
       salaries b
WHERE  a.emp_no = b.emp_no
       AND b.to_date = '9999-01-01'
       AND ( a.emp_no, b.salary ) IN (SELECT emp_no,
                                             salary
                                      -- 'in(sub_query)' <-> ='any(sub_query)'
                                      FROM   salaries
                                      WHERE  to_date = '9999-01-01'
                                             AND salary >= 50000);

โœ”๏ธ ์„œ๋ธŒ์ฟผ๋ฆฌ์—์„œ SELECTํ•œ ์†์„ฑ์œผ๋กœ ์ด๋ฃจ์–ด์ง„ ํ…Œ์ด๋ธ”์„ ์ฐธ์กฐ ํ•˜์—ฌ WHERE์ ˆ์—์„œ ํ•ด๋‹น ์ปฌ๋Ÿผ์„ ์„ ํƒํ•ด ํŒ๋ณ„ ํ•  ์ˆ˜ ์žˆ๋‹ค.