๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
DB/MySQL

[MySQL] ์„œ๋ธŒ์ฟผ๋ฆฌ( subquery) ๋ž€?

by yunamom 2022. 3. 29.
๋ฐ˜์‘ํ˜•

mysql

โœจ์„œ๋ธŒ์ฟผ๋ฆฌ(subquery)

์„œ๋ธŒ์ฟผ๋ฆฌ(subquery)๋ž€ ๋‹ค๋ฅธ ์ฟผ๋ฆฌ ๋‚ด๋ถ€์— ํฌํ•จ๋˜์–ด ์žˆ๋Š” SELETE ๋ฌธ์„ ์˜๋ฏธํ•ฉ๋‹ˆ๋‹ค.

 

์„œ๋ธŒ์ฟผ๋ฆฌ๋ฅผ ํฌํ•จํ•˜๊ณ  ์žˆ๋Š” ์ฟผ๋ฆฌ๋ฅผ ์™ธ๋ถ€์ฟผ๋ฆฌ(outer query)๋ผ๊ณ  ๋ถ€๋ฅด๋ฉฐ, ์„œ๋ธŒ์ฟผ๋ฆฌ๋Š” ๋‚ด๋ถ€์ฟผ๋ฆฌ(inner query)๋ผ๊ณ ๋„ ๋ถ€๋ฆ…๋‹ˆ๋‹ค.

 

์„œ๋ธŒ์ฟผ๋ฆฌ๋Š” ๋ฐ˜๋“œ์‹œ ๊ด„ํ˜ธ(())๋กœ ๊ฐ์‹ธ์ ธ ์žˆ์–ด์•ผ๋งŒ ํ•ฉ๋‹ˆ๋‹ค.

 

MySQL์—์„œ ์„œ๋ธŒ์ฟผ๋ฆฌ๋ฅผ ํฌํ•จํ•  ์ˆ˜ ์žˆ๋Š” ์™ธ๋ถ€์ฟผ๋ฆฌ๋Š” SELECT, INSERT, UPDATE, DELETE, SET, DO ๋ฌธ์ด ์žˆ์Šต๋‹ˆ๋‹ค.

 

์ด๋Ÿฌํ•œ ์„œ๋ธŒ์ฟผ๋ฆฌ๋Š” ๋˜ ๋‹ค์‹œ ๋‹ค๋ฅธ ์„œ๋ธŒ์ฟผ๋ฆฌ ์•ˆ์— ํฌํ•จ๋  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 


์„œ๋ธŒ์ฟผ๋ฆฌ์˜ ํŠน์ง•

์„œ๋ธŒ์ฟผ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์žฅ์ ์„ ์–ป์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

1. ์„œ๋ธŒ์ฟผ๋ฆฌ๋Š” ์ฟผ๋ฆฌ๋ฅผ ๊ตฌ์กฐํ™”์‹œํ‚ค๋ฏ€๋กœ, ์ฟผ๋ฆฌ์˜ ๊ฐ ๋ถ€๋ถ„์„ ๋ช…ํ™•ํžˆ ๊ตฌ๋ถ„ํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•ด์ค๋‹ˆ๋‹ค.

2. ์„œ๋ธŒ์ฟผ๋ฆฌ๋Š” ๋ณต์žกํ•œ JOIN์ด๋‚˜ UNION๊ณผ ๊ฐ™์€ ๋™์ž‘์„ ์ˆ˜ํ–‰ํ•  ์ˆ˜ ์žˆ๋Š” ๋˜ ๋‹ค๋ฅธ ๋ฐฉ๋ฒ•์„ ์ œ๊ณตํ•ฉ๋‹ˆ๋‹ค.

3. ์„œ๋ธŒ์ฟผ๋ฆฌ๋Š” ๋ณต์žกํ•œ JOIN์ด๋‚˜ UNION ๋ณด๋‹ค ์ข€ ๋” ์ฝ๊ธฐ ํŽธํ•ฉ๋‹ˆ๋‹ค.

# ์„œ๋ธŒ ์ฟผ๋ฆฌ

# ๋ฌธ์ œ) bookํ…Œ์ด๋ธ”์—์„œ ์ „์ฒด ํ‰๊ท  ๊ฐ€๊ฒฉ๋ณด๋‹ค ๋” ๋†’์€ ๋„์„œ์ •๋ณด ๊ฐ€์ ธ์˜ค๊ธฐ
SELECT AVG(book_price) FROM book;	-- 22690.4762
SELECT book_price FROM book
WHERE book_price > (SELECT AVG(book_price) FROM book);


# bookํ…Œ์ด๋ธ”์—์„œ ๊ฐ€์žฅ ๊ฐ€๊ฒฉ์ด ๋†’์€ ๋„์„œ ์ •๋ณด ๊ฐ€์ ธ์˜ค๊ธฐ
SELECT * FROM book
WHERE book_price = (SELECT MAX(book_price) FROM book);

FROM ์ ˆ์˜ ์„œ๋ธŒ์ฟผ๋ฆฌ

์„œ๋ธŒ์ฟผ๋ฆฌ๋Š” SELECT ๋ฌธ์˜ FROM ์ ˆ์—์„œ๋„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

์ด๋•Œ ์„œ๋ธŒ์ฟผ๋ฆฌ์— ์˜ํ•ด ์„ ํƒ๋œ ๊ฒฐ๊ณผ ์ง‘ํ•ฉ์€ FROM ์ ˆ์—์„œ ํ•˜๋‚˜์˜ ํ…Œ์ด๋ธ”๋กœ์จ ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค.

 

๐Ÿ’กSELECT ๋ฌธ์˜ FROM ์ ˆ์—์„œ ์‚ฌ์šฉ๋˜๋Š” ๋ชจ๋“  ํ…Œ์ด๋ธ”์—๋Š” ์ด๋ฆ„์„ ์ •์˜ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.

 

SELECT ...
FROM (์„œ๋ธŒ์ฟผ๋ฆฌ) [AS] ์ด๋ฆ„
...

 

 

300x250

์ฝ”๋“œ