各位大神,问一个问题,关于orcale的层级查询的,我想新建一个字段,用来代表父子关系,例如 0001 代表父节点,那00010001和00010002代表子节点,以此类推,这种怎么通过已有的父子关系生成,求解答,谢谢。
例如
id parent_id catId
1 -1 0001
2 1 00010001
3 1 00010002
4 3 000100020001
5 3 000100020002
求解catid怎么生成
注:根节点0001为初始化的数据
------解决思路----------------------
--第一步分组后加前缀标号
UPDATE TABLE_NAME TT
SET CATID =
(SELECT CASE
WHEN ROW_NUM < 10 THEN
'000'
WHEN ROW_NUM < 100 THEN
'00'
WHEN ROW_NUM < 1000 THEN
'0'
ELSE
''
END
------解决思路----------------------
BB.ROW_NUM
FROM (SELECT AA.ID,
AA.PARENT_ID,
ROW_NUMBER() OVER(PARTITION BY AA.PARENT_ID ORDER BY ID) ROW_NUM
FROM TABLE_NAME AA) BB
WHERE BB.ID = TT.ID);
--第二步 因为parent_id为-1的不需要改变 则改变下一级的 CATID
UPDATE TABLE_NAME TT
SET CATID =
(SELECT AA.CATID FROM TABLE_NAME AA WHERE AA.ID = TT.PARENT_ID)
------解决思路----------------------
--找到父节点的CATID 并合并
TT.CATID
WHERE TT.PARENT_ID IN (SELECT ID FROM TABLE_NAME WHERE PARENT_ID = -1) --父节点为第一级的id
;
--第三步 更改第三级
UPDATE TABLE_NAME TT
SET CATID =
(SELECT AA.CATID FROM TABLE_NAME AA WHERE AA.ID = TT.PARENT_ID)
------解决思路----------------------
--找到父节点的CATID 并合并
TT.CATID
WHERE TT.PARENT_ID IN
(SELECT ID
FROM TABLE_NAME BB
WHERE BB.PARENT_ID IN
(SELECT ID FROM TABLE_NAME WHERE PARENT_ID = -1)) --父节点为第二级的id
;
--以此类推 有多少级就执行多少次
------解决思路----------------------
改一下,不用加字段了。直接更新
UPDATE 表名 T
SET T.CATID =
(WITH TMP AS (SELECT ID,
REPLACE(SYS_CONNECT_BY_PATH(TO_CHAR(RK, 'fm0000'),
','),
',') CAT
FROM (SELECT ID,
PARENT_ID,
ROW_NUMBER() OVER(PARTITION BY PARENT_ID ORDER BY ID) RK
FROM 表名)
START WITH PARENT_ID = -1
CONNECT BY PRIOR ID = PARENT_ID)
SELECT CAT FROM TMP X WHERE X.ID = T.ID);