๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ’ป Computer Science/๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค

[๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค] ๊ณ„์ธตํ˜• ์ฟผ๋ฆฌ์˜ ORDER SIBLINGS BY ๋ž€? ์˜ˆ์ œ ํฌํ•จ

by Jay Din 2024. 8. 23.
728x90
๋ฐ˜์‘ํ˜•

ORDER SIBLINGS BY ๋ž€?

ORDER SIBLINGS BY๋Š” Oracle SQL์—์„œ ๊ณ„์ธตํ˜• ์ฟผ๋ฆฌ(Hierarchical Query)๋ฅผ ์‚ฌ์šฉํ•  ๋•Œ, ๊ฐ™์€ ๋ถ€๋ชจ๋ฅผ ๊ฐ€์ง„ ํ˜•์ œ ๋…ธ๋“œ๋“ค(Sibilings)์„ ํŠน์ • ๊ธฐ์ค€์— ๋”ฐ๋ผ ์ •๋ ฌํ•˜๋Š”๋ฐ ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค.

์ด๋Š” CONNECT BY ์ ˆ๊ณผ ํ•จ๊ป˜ ์‚ฌ์šฉ๋˜๋ฉฐ, ๊ณ„์ธต ๊ตฌ์กฐ ๋‚ด์—์„œ ๊ฐ™์€ ๋ ˆ๋ฒจ(๊ฐ™์€ ๋ถ€๋ชจ๋ฅผ ๊ณต์œ ํ•˜๋Š”) ํ˜•์ œ๋“ค๋งŒ ์ •๋ ฌํ•˜๋Š” ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•ฉ๋‹ˆ๋‹ค.

 

๊ณ„์ธตํ˜• ์ฟผ๋ฆฌ์˜ ๊ธฐ๋ณธ ๊ฐœ๋…

Oracle์˜ ๊ณ„์ธตํ˜• ์ฟผ๋ฆฌ๋Š” ํŠธ๋ฆฌ ๊ตฌ์กฐ์™€ ๊ฐ™์€ ๊ณ„์ธต์  ๋ฐ์ดํ„ฐ๋ฅผ ์ฒ˜๋ฆฌํ•˜๊ธฐ ์œ„ํ•ด ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค.

CONNECT BY ์ ˆ์„ ์‚ฌ์šฉํ•˜์—ฌ ๋ถ€๋ชจ-์ž์‹ ๊ด€๊ณ„๋ฅผ ์ •์˜ํ•˜๊ณ , START WITH ์ ˆ์„ ์‚ฌ์šฉํ•˜์—ฌ ํŠธ๋ฆฌ์˜ ๋ฃจํŠธ ๋…ธ๋“œ๋ฅผ ์ง€์ •ํ•ฉ๋‹ˆ๋‹ค.

  • START WITH : ํŠธ๋ฆฌ ๊ตฌ์กฐ์—์„œ ์‹œ์ž‘ํ•  ๋ฃจํŠธ ๋…ธ๋“œ๋ฅผ ์ง€์ •ํ•ฉ๋‹ˆ๋‹ค.
  • CONNECT BY PRIOR : ๋ถ€๋ชจ์™€ ์ž์‹ ๊ฐ„์˜ ๊ด€๊ณ„๋ฅผ ์ •์˜ํ•ฉ๋‹ˆ๋‹ค.

 

ODER SIBLINGS BY ์˜ ์—ญํ• 

 

  • ORDER SIBLINGS BY๋Š” ๊ฐ ๊ณ„์ธต ๋ ˆ๋ฒจ์—์„œ ํ˜•์ œ ๋…ธ๋“œ๋“ค์„ ์ •๋ ฌํ•˜๋Š” ๋ฐ ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค.
  • ์ด ๊ตฌ๋ฌธ์€ ORDER BY ์ ˆ๊ณผ ์œ ์‚ฌํ•˜์ง€๋งŒ, ๊ณ„์ธต ๊ตฌ์กฐ์˜ ๋™์ผํ•œ ๋ ˆ๋ฒจ(ํ˜•์ œ ๋…ธ๋“œ๋“ค)์—์„œ๋งŒ ์ •๋ ฌ์ด ์ด๋ฃจ์–ด์ง‘๋‹ˆ๋‹ค.
  • ์ฆ‰, ํŠธ๋ฆฌ ๊ตฌ์กฐ ์ „์ฒด๋ฅผ ์ •๋ ฌํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๋ผ, ๊ฐ ๊ณ„์ธต ๋ ˆ๋ฒจ์—์„œ๋งŒ ์ •๋ ฌ์ด ์ด๋ฃจ์–ด์ง€๋ฏ€๋กœ, ๊ณ„์ธต ๊ตฌ์กฐ๊ฐ€ ๋ณด์กด๋œ ์ƒํƒœ์—์„œ ๋…ธ๋“œ๋“ค์„ ์›ํ•˜๋Š” ์ˆœ์„œ๋กœ ๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

 

์˜ˆ์‹œ

ํ…Œ์ด๋ธ” TAB1 ์˜ˆ์‹œ ๋ฐ์ดํ„ฐ:

C1 C2 C3
1 NULL A
2 1 B
3 1 C
4 2 D
5 2 E
6 3 F
7 3 G

์ฟผ๋ฆฌ

SELECT C3
FROM TAB1
START WITH C2 IS NULL
CONNECT BY PRIOR C1 = C2
ORDER SIBLINGS BY C3 DESC;

 

์ด ์ฟผ๋ฆฌ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๊ณ„์ธต ๊ตฌ์กฐ๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค:

  • ๋ฃจํŠธ ๋…ธ๋“œ(C2 IS NULL): C1 = 1, C3 = A
    • ์ž์‹ ๋…ธ๋“œ: C1 = 2, C3 = B์™€ C1 = 3, C3 = C
      • C1 = 2์˜ ์ž์‹: C1 = 4, C3 = D์™€ C1 = 5, C3 = E
      • C1 = 3์˜ ์ž์‹: C1 = 6, C3 = F์™€ C1 = 7, C3 = G

 

ORDER SIBLINGS BY C3 DESC๊ฐ€ ์ ์šฉ๋œ ๊ฒฐ๊ณผ:

  1. ๋ฃจํŠธ ๋ ˆ๋ฒจ: A (C3 = A)
    • ์ฒซ ๋ฒˆ์งธ ๋ ˆ๋ฒจ์˜ ํ˜•์ œ ๋…ธ๋“œ: C (C3 = C), B (C3 = B) ← C3 DESC ๊ธฐ์ค€์œผ๋กœ ์ •๋ ฌ
      • ๋‘ ๋ฒˆ์งธ ๋ ˆ๋ฒจ์˜ ํ˜•์ œ ๋…ธ๋“œ (B์˜ ์ž์‹): E (C3 = E), D (C3 = D) ← C3 DESC ๊ธฐ์ค€์œผ๋กœ ์ •๋ ฌ
      • ๋‘ ๋ฒˆ์งธ ๋ ˆ๋ฒจ์˜ ํ˜•์ œ ๋…ธ๋“œ (C์˜ ์ž์‹): G (C3 = G), F (C3 = F) ← C3 DESC ๊ธฐ์ค€์œผ๋กœ ์ •๋ ฌ

 

๊ฒฐ๊ณผ์ ์œผ๋กœ, ์ •๋ ฌ๋œ ์ˆœ์„œ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค:

C3
A
C
G
F
B
E
D

 

์š”์•ฝ

  • **ORDER SIBLINGS BY**๋Š” ๊ฐ™์€ ๋ถ€๋ชจ๋ฅผ ๊ฐ€์ง„ ํ˜•์ œ ๋…ธ๋“œ๋“ค๋งŒ์„ ์ง€์ •๋œ ๊ธฐ์ค€์œผ๋กœ ์ •๋ ฌํ•˜๋Š” ์ ˆ์ž…๋‹ˆ๋‹ค.
  • ๊ณ„์ธตํ˜• ๋ฐ์ดํ„ฐ์—์„œ ์ „์ฒด ํŠธ๋ฆฌ์˜ ์ˆœ์„œ๋ฅผ ๋ฐ”๊พธ์ง€ ์•Š๊ณ , ๊ฐ ๋ ˆ๋ฒจ์—์„œ ํ˜•์ œ ๋…ธ๋“œ๋“ค๋งŒ ์ •๋ ฌํ•ฉ๋‹ˆ๋‹ค.
  • ์ด ์ ˆ์€ ๊ณ„์ธต ๊ตฌ์กฐ๋ฅผ ์œ ์ง€ํ•˜๋ฉด์„œ ๋ฐ์ดํ„ฐ์˜ ์ˆœ์„œ๋ฅผ ๊ด€๋ฆฌํ•  ๋•Œ ๋งค์šฐ ์œ ์šฉํ•ฉ๋‹ˆ๋‹ค.

 

 

 

728x90
๋ฐ˜์‘ํ˜•