" MYSQL ์ฝ”๋”ฉํ…Œ์ŠคํŠธ์—ฐ์Šต: ์ž…์–‘ ์‹œ๊ฐ ๊ตฌํ•˜๊ธฐ (2) (์žฌ๊ท€์ฟผ๋ฆฌ)
๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
ํ˜„์—…๊ด‘๊ณ ์ธ/๊ฐ์ข…๊ฟ€ํŒ

MYSQL ์ฝ”๋”ฉํ…Œ์ŠคํŠธ์—ฐ์Šต: ์ž…์–‘ ์‹œ๊ฐ ๊ตฌํ•˜๊ธฐ (2) (์žฌ๊ท€์ฟผ๋ฆฌ)

by ๋…๋”˜ 2021. 1. 13.
728x90
๋ฐ˜์‘ํ˜•

 

 

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ์ž…์–‘ ์‹œ๊ฐ ๊ตฌํ•˜๊ธฐ(2)

ANIMAL_OUTS ํ…Œ์ด๋ธ”์€ ๋™๋ฌผ ๋ณดํ˜ธ์†Œ์—์„œ ์ž…์–‘ ๋ณด๋‚ธ ๋™๋ฌผ์˜ ์ •๋ณด๋ฅผ ๋‹ด์€ ํ…Œ์ด๋ธ”์ž…๋‹ˆ๋‹ค. ANIMAL_OUTS ํ…Œ์ด๋ธ” ๊ตฌ์กฐ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์œผ๋ฉฐ, ANIMAL_ID, ANIMAL_TYPE, DATETIME, NAME, SEX_UPON_OUTCOME๋Š” ๊ฐ๊ฐ ๋™๋ฌผ์˜ ์•„์ด๋””, ์ƒ๋ฌผ

programmers.co.kr

ํ•ด๋‹น ๊ธ€์€ Programmers ์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต์„ ํ† ๋Œ€๋กœ MYSQL ๋กœ ์ž‘์„ฑ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.

 


Q ๋ฌธ์ œ:  ์ž…์–‘ ์‹œ๊ฐ ๊ตฌํ•˜๊ธฐ (2) 

 ๋ฌธ์ œํ’€์ด : 

WITH RECURSIVE
            NEWTABLE AS 
              ( SELECT 0 AS HOUR
                UNION ALL
                SELECT HOUR + 1
                FROM NEWTABLE
                WHERE HOUR < 23 )
SELECT      NEWTABLE.HOUR, COUNT(ani.ANIMAL_ID) AS COUNT
FROM        NEWTABLE
LEFT JOIN   ANIMAL_OUTS AS ani
ON          NEWTABLE.hour = HOUR(ani.DATETIME)
GROUP BY    NEWTABLE.hour

 

ํ•ด๋‹น๋ฌธ์ œ๋Š” CTE(๊ณตํ†ตํ…Œ์ด๋ธ”)์‹์„ ์‚ฌ์šฉํ•˜๋Š” ์žฌ๊ท€์ฟผ๋ฆฌ (Recursive Query)๊ฐ€ ์‚ฌ์šฉ๋˜์—ˆ์œผ๋ฉฐ ์œ„ ์ฝ”๋“œ๋Š”

์•„๋ž˜ ๋งํฌ๋Œ“๊ธ€์„ ์ธ์šฉํ•˜์—ฌ ์ •๋ฆฌํ•ด๋ณด์•˜์Šต๋‹ˆ๋‹ค.  โ–ผ ์•„๋ž˜ ๋งํฌ 

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr


E ์ƒ์„ธ์„ค๋ช…

1. WITH RECURSIVE ๋ฅผ ์ด์šฉํ•˜์—ฌ 01์‹œ์—์„œ 23์‹œ๊นŒ์ง€ ์กด์žฌํ•˜๋Š” HOUR์ปฌ๋Ÿผ ํ…Œ์ด๋ธ”์„ ์ƒ์„ฑํ•ด์ค๋‹ˆ๋‹ค. 

2. ๊ธฐ๋ณธ ANIMAL_OUTS ํ…Œ์ด๋ธ”๊ณผ LEFT JOIN(์กฐ์ธ)์„ ํ•ด์ค๋‹ˆ๋‹ค.

3. GROUP BY SQL๋ฌธ์„ ์ด์šฉํ•˜์—ฌ HOUR(์‹œ๊ฐ„)์„ ๊ทธ๋ฃนํ™”๋ฅผ ํ•ด์ค๋‹ˆ๋‹ค.

4. SELECT๋ฅผ ์ด์šฉํ•˜์—ฌ ์‹œ๊ฐ„๋Œ€์™€ ์‹œ๊ฐ„๋Œ€๋ณ„ ์ž…์–‘๋œ ๊ฐœ์ˆ˜๋ฅผ ํŒŒ์•…ํ•ฉ๋‹ˆ๋‹ค.

 

 

RECURSIVE QUERY(์žฌ๊ท€์ฟผ๋ฆฌ) : 

์œ„ SQL๋ฌธ์— ์ž‘์„ฑ๋œ RECURSIVE(์žฌ๊ท€)๋Š” ์˜์–ด๋กœ๋Š” ๋ฐ˜๋ณต[๋˜ํ’€์ด]๋˜๋Š” ๋œป์œผ๋กœ ์ด๋Ÿฌํ•œ SQL๋ฌธ์„ RECURSIVE FUNCTION(์žฌ๊ท€ํ•จ์ˆ˜)๊ฐ€ ์‚ฌ์šฉ๋˜์—ˆ๋‹ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค. ์žฌ๊ท€ํ•จ์ˆ˜๋ฅผ ์กฐ๊ธˆ ๋” ์„ค๋ช…ํ•ด๋ณด์ž๋ฉด ์ž๊ธฐ ์ž์‹ ์„ ํ˜ธ์ถœํ•˜์—ฌ ์ด์šฉํ•˜๋Š” ํ•จ์ˆ˜์ž…๋‹ˆ๋‹ค.

WITH RECURSIVE
		CTE_ํ…Œ์ด๋ธ”๋ช… AS
        (SELECT ๋ฌธ 
       	)
SELECT ๋ฌธ 
FROM ํ…Œ์ด๋ธ”๋ช…1
LEFT JOIN ํ…Œ์ด๋ธ”๋ช…2
ON ํ…Œ์ด๋ธ”1.๊ธฐ์ค€์ปฌ๋Ÿผ = ํ…Œ์ด๋ธ”2.๊ธฐ์ค€์ปฌ๋Ÿผ 
GROUP BY ๊ทธ๋ฃน๊ธฐ์ค€ ์ปฌ๋Ÿผ โ€‹

 

CTE : 

CTE(Common Table Exprssions)๋Š” ์šฐ๋ฆฌ๋‚˜๋ผ๋กœ ํ’€์–ด์“ฐ์ž๋ฉด ๊ณตํ†ต ํ…Œ์ด๋ธ” ์‹์ด๋ผ๊ณ  ํ•ฉ๋‹ˆ๋‹ค. 

CTE๊ฐ€ SQL์„œ๋ฒ„์—์„œ ์‚ฌ์šฉ๋ ๋•Œ๋Š” ์ฃผ๋กœ ๋ณต์žกํ•œ ์กฐ์ธ๋ฌธ, ์„œ๋ธŒ์ฟผ๋ฆฌ๋ฅผ ๊ฐ„์†Œํ™”ํ•˜๊ธฐ์œ„ํ•ด ์‚ฌ์šฉ๋˜๋ฉฐ

๊ทธ๋ฆฌ๊ณ  ๊ณ„์ธต์  ๋ฐ์ดํ„ฐ๋ฅผ ํ‘œํ˜„ํ• ๋•Œ ์ฃผ๋กœ ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค.

 

 

LEFT JOIN (LEFT OUTER JOIN) :

 

์™ผ์ชฝ์™ธ๋ถ€์กฐ์ธ์ด๋ผ๋„ ๋งํ•˜๋ฉฐ

์™ผ์ชฝํ…Œ์ด๋ธ” ์ „์ฒด๊ฐ’๊ณผ ์™ผ์ชฝํ…Œ์ด๋ธ”๊ณผ ์ค‘์ฒฉ๋˜๋Š” ์˜ค๋ฅธ์ชฝํ…Œ์ด๋ธ”์— ๊ฐ’๋“ค์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. 

 

๋ฐ˜์‘ํ˜•