請問各位大大~
今天有一個選單表長這樣
選單代碼 選單名稱 選單層級 上層選單
MENU_CODE MENU_NAME DEPTHS
1. M0 系統 1 NULL
2. M00 權限 2 M0
3. M00-00 角色權限 3 M00
4. M00-01 角色審核 3 M00
需要用遞迴的方式,產出類似以下的表
選單 名稱 選單 名稱 選單 名稱
1. M0 系統 M00 權限
2. M0 系統 M00 權限 M00-00 角色權限
3. M0 系統 M00 權限 M00-01 角色審核
想破腦袋了,寫不出來,請各位大大幫助
補充:我的版本可以用CTE
create table it220626 (
id int not null primary key
, code text not null
, name text not null
, parent int
);
insert into it220626 values
(1, 'M0', '系統', NULL),
(2, 'M00', '權限', 1),
(3, 'M00-00', '角色權限', 2),
(4, 'M00-01', '角色審核', 2);
with recursive c as (
select id
, '[' || code || ',' || name || ']' as path
from it220626
where parent is null
union all
select i.id
, c.path || ' -> ' || '[' || i.code || ',' || i.name || ']'
from it220626 i
join c
on i.parent = c.id
)
select id
, path
from c;
id | path
----+----------------------------------------------
1 | [M0,系統]
2 | [M0,系統] -> [M00,權限]
3 | [M0,系統] -> [M00,權限] -> [M00-00,角色權限]
4 | [M0,系統] -> [M00,權限] -> [M00-01,角色審核]
(4 rows)
只有三層的話,不用遞廻
create table it220626 (
id int not null primary key
, code text not null
, name text not null
, parent int
);
insert into it220626 values
(1, 'M0', '系統', NULL),
(2, 'M00', '權限', 1),
(3, 'M00-00', '角色權限', 2),
(4, 'M00-01', '角色審核', 2);
Select
(case When i2.parent Is Null Then i2.code Else i1.code End) as 選單1
, (case When i2.parent Is Null Then i2.name Else i1.name End) as 名稱1
, (Case When i2.parent Is Null Then i3.code Else i2.code End) as 選單2
, (Case When i2.parent Is Null Then i3.name Else i2.name End) as 名稱2
, (Case When i2.parent Is Null Then '' Else i3.code End) as 選單3
, (Case When i2.parent Is Null Then '' Else i3.name End) as 名稱3
--, i1.parent as p1, i2.parent as p2, i3.parent as p3
From it220626 i3
Inner Join it220626 i2 On i3.parent = i2.id
Left Outer Join it220626 i1 On i2.parent = i1.id
Order by i1.parent, i2.parent, i3.parent