๊ด€๋ฆฌ ๋ฉ”๋‰ด

JiYoung Dev ๐Ÿ–ฅ

[database ๊ณ ๊ธ‰] ๊ณ„์ธต ์ฟผ๋ฆฌ (2023.08.09) ๋ณธ๋ฌธ

full stack/database

[database ๊ณ ๊ธ‰] ๊ณ„์ธต ์ฟผ๋ฆฌ (2023.08.09)

Shinjio 2023. 8. 9. 16:40

๊ณ„์ธต ์ฟผ๋ฆฌ ํ™œ์šฉ์‹œ ๋ฉ”๋‰ด, ๊ฒŒ์‹œํŒ์˜ ๋Œ“๊ธ€, ๋Œ€๋Œ“๊ธ€์„ ๋งŒ๋“ค ์ˆ˜ ์žˆ์Œ 

 

 

 

์˜ˆ์‹œ ์ฟผ๋ฆฌ

 

SELECT ๋ฉ”๋‰ดID 
, ์ƒ์œ„๋ฉ”๋‰ดID 
, ๋ฉ”๋‰ด์ด๋ฆ„
 , LEVEL 
, LPAD(' ' , ( LEVEL -1 ) * 2 , ' ' ) || ๋ฉ”๋‰ด์ด๋ฆ„
 FROM ๋ฉ”๋‰ด
WHERE 1=1 -- WHERE ์กฐ๊ฑด์ด ์—†์œผ๋ฉด ๋”ฐ๋กœ ์•ˆ์จ๋„ ๋จ
START WITH ์ƒ์œ„๋ฉ”๋‰ดID IS NULL 
CONNECT BY NOCYCLE ์ƒ์œ„๋ฉ”๋‰ดID = PRIOR ๋ฉ”๋‰ดID
ORDER SIBLINGS BY ๋ฉ”๋‰ดID ;

 

์…€ํ”„ ์กฐ์ธ(SELF JOIN)

 

SELECT * 
  FROM ๋ฉ”๋‰ด A, ๋ฉ”๋‰ด B
 WHERE A.์ƒ์œ„๋ฉ”๋‰ดID = B.๋ฉ”๋‰ดID;
 
-- ์…€ํ”„์กฐ์ธ (๊ณ„์ธต ์ฟผ๋ฆฌ๊ฐ€ ์—†๋˜ ์‹œ์ ˆ์— ๊ณ„์ธต์„ ๊ตฌํ˜„ํ•˜๊ธฐ ์œ„ํ•ด ์‚ฌ์šฉ)

 

 

๋Œ€๋Œ“๊ธ€ ๊ตฌํ˜„

 

SELECT ๋Œ“๊ธ€ID
 , ์ƒ์œ„๊ธ€
 , ์ž‘์„ฑ๊ธ€
 , CASE WHEN ์ž‘์„ฑ๊ธ€ IS NULL THEN 
 ( SELECT ๊ฒŒ์‹œ๋ฌผ๋‚ด์šฉ
 FROM ๊ฒŒ์‹œํŒ
 WHERE ๊ฒŒ์‹œ๊ธ€ID = ์ƒ์œ„๊ธ€ ) 
 ELSE LPAD('ใ…ฃ-' , LEVEL*2 , ' ') || ์ž‘์„ฑ๊ธ€
 END 
 AS ๊ณ„์ธต์ฟผ๋ฆฌ๊ฒฐ๊ณผ
 , LEVEL 
 FROM ๋Œ“๊ธ€
START WITH ์ž‘์„ฑ๊ธ€ IS NULL 
CONNECT BY PRIOR ๋Œ“๊ธ€ID = ์ƒ์œ„๊ธ€ ;