利用start with connect by 查询子节点和父节点数据显示为树状形
前段时间做了一个根据子节点和父节点查询出树状型
表数据:
要实现的结果:
实现的sql:
select rpad('---', (level - 1) * 3, '---') || name as name, id
from t_nscreen_region
start with id = 1
connect by nocycle prior id = parent_id
order SIBLINGS BY id;
其中函数理解:
1.PRIOR
阶层查询的CONNECY BY condition的条件式需要用到PRIOR来指定父节点
2.CONNECT BY
通过CONNECT BY子句定义子节点和父节点的关系
3.start with
通过start with 指定根节点(不指定start with会出现重复记,不指定NOCYCLE没事)
4.LEVEL
通过LEVEL虚拟列表示节点的关系
5.rpad(string,padded_length,[pad_string])函数
从右边对字符串使用指定的字符进行填充
string:表示要追加的字符,
padded_length:表示追加后的长度
pad_string:表示string字符长度不够padded_length时,取pad_string的字符,默认为空格
6.lpad( string1, padded_length, [ pad_string ] )函数
从左边对字符串使用指定的字符进行填充
string1:源字符串
padded_length:最终返回的字符串的长度,如果最终返回的字符串的长度比源字符串的小,那么此函数实际上对源串进行截断处理
pad_string:用于填充的字符,可以不填,默认为空字符
7.order SIBLINGS BY id :按id进行排序