oracle的递归写法:地区层级
前言
mysql的递归看我另一篇博文:https://www.cnblogs.com/daen/p/17252369.html
表结构
数据
查询子节点
示例
SELECT
cx1.*
FROM
PHCP_CITY cx1
WHERE
cx1.IS_ENABLE = 1 START WITH cx1.CITY_CODE = '370100' CONNECT BY PRIOR cx1.CITY_CODE = cx1.PARENT_ID
结果
不含自己的写法
加个不等于即可
查询父节点
示例
SELECT
cx1.*
FROM
PHCP_CITY cx1
WHERE
cx1.IS_ENABLE = 1 START WITH cx1.CITY_CODE = '370112' CONNECT BY cx1.CITY_CODE = PRIOR cx1.PARENT_ID
结果
不含自己的写法
加个不等于即可
查询子节点和父节点的区别
其实就是将 PRIOR
放到了PARENT_ID
前面而已
多行合并一行
就是我输入一个地区CODE,然后获取到他的所有的父级的名称,拼接成一个字符串
写法一
WITH temp AS (
SELECT
cx1.*
FROM
PHCP_CITY cx1
WHERE
cx1.IS_ENABLE = 1 START WITH cx1.CITY_CODE = '370112' CONNECT BY cx1.CITY_CODE = PRIOR cx1.PARENT_ID
) SELECT
listagg ( CITY_NAME, '#' ) within GROUP ( ORDER BY IS_ENABLE, CITY_LEVEL ) AS brands
FROM
temp
GROUP BY
IS_ENABLE;
写法二
SELECT
listagg ( CITY_NAME, '#' ) within GROUP ( ORDER BY IS_ENABLE, CITY_LEVEL ) AS brands
FROM
(
SELECT
cx1.CITY_CODE,
CITY_NAME,
IS_ENABLE,
CITY_LEVEL
FROM
PHCP_CITY cx1
WHERE
cx1.IS_ENABLE = 1 START WITH cx1.CITY_CODE = '370112' CONNECT BY cx1.CITY_CODE = PRIOR cx1.PARENT_ID
ORDER BY
CITY_LEVEL
)
GROUP BY
IS_ENABLE;