|
我有一张表category,如下所示:+ O3 z* _: f3 E ^! f; l5 ]
id title ParentID
6 l/ m- Y1 u& ]* q# z" H% Q# Q1 C1 0( w+ w$ P$ L, J9 i/ T7 m. b( S8 }* x+ E
2 C2 0# K$ u$ ^4 R8 n. }- C% O
3 C3 0
4 `) [- Z2 f5 s# u9 H4 C4 2* V/ Z; x+ Y1 q9 h. K8 S8 B
5 C5 1) M5 |" i. H4 k3 o: g3 h0 H# w* R& u
6 C6 31 _$ K0 c Z- O# n+ O& { P! g, P3 O
7 C7 4
, D$ f5 S9 d, x' m1 j2 ^我想要结果" }3 V1 ^; D" D4 I5 k- N5 x8 d5 A
id title ParentID Level
' S* f" a) \5 D ^& x/ N; @1 C1 0 03 z% g. a3 w; ]
5 C5 1 1
1 G9 ~0 l- p6 N1 X0 S2 C2 0 0
1 Y$ W8 N8 a5 E3 m" X4 C4 2 1
# y% l# k P0 x9 h; H7 C7 4 2
2 R% E- u7 T8 t0 A. H1 d3 C3 0 0/ r6 L. c; o- u, ]7 D) H
6 C6 3 1& t" [3 T9 n- c/ h4 L0 M6 b& b
我怎么能得到这个结果?! C4 T; p S: H0 v/ ~ q, E, F
订单说明:我想要结果低于其父项目的项目。& j' z' J- ~ q
" B- W, ~. I* u
解决方案:8 w; W. m' P7 o
$ b% j1 |8 ] k! \/ A
' W0 R. \5 R5 l Z. Q& ?# g
# a, ]! h" e& o' |7 R! a P: g: c 该答案假定您使用的是SQL Server 2008或更高版本。1 J- E2 c) z9 `* I
使用递归CTE并构建按顺序使用的ID字符串,作为层次结构ID。
! E% z( L7 Q6 Ywith C as
D; h2 \ b# N+ o3 F+ ]0 Z: ?(
7 R1 S @) p1 O) P. K+ u select id,1 Y: Y( t _% m4 L
title,- {' N$ U, ~! | [* `
parentid,3 c) H) J/ k; G
'/'+cast(id as varchar(max))+'/' as sort, y; j5 T, _% k% i1 `% P( B, ~- X
1 as lvl
5 I J5 @4 |$ `- h! e& E$ w from YourTable1 s. d A6 ^7 R7 @) ^
where parentid = 0) Q+ N5 j7 R0 A& o7 n- D
union all
" U J5 S; J8 J4 i" p# Q select T.id,
9 ~; j" @# l! O/ }( |8 Y T.title,
" x0 b: b$ K) s8 D T.parentid,
1 [; d: P1 r( x4 W2 |* b9 o C.sort + cast(T.id as varchar(10)) + '/',6 h% `& B/ h6 ]& k6 H1 F# x
C.lvl + 1
4 O! I( W# P% ~! |* Z8 W' ^. o from YourTable as T/ j2 R G5 w& c9 {/ J% K& K2 u
inner join C
/ \6 ^1 Y4 V. W1 |8 l" B on T.parentid = C.id
- ]9 K* \8 I9 y9 i1 T; q)
2 H5 ~4 i; Q' G: W1 X; a& |select id,$ J! M! T4 X- F& k( a& h4 T8 k5 ~
title,
b# E! q* H, C6 V parentid,. t1 k" ?+ P& K; q, P
lvl,
% T4 U' z# j! b0 l! b( x9 W sort3 x. c4 _. D2 s, H! f8 G# E3 z- Q
from C& B! p% r1 _: e, A9 Q) i
order by cast(sort as hierarchyid)
: n$ ^" g4 a* ]7 h9 @* Y9 HSQL小提琴 |
|