一、postgresql
表格式如下

讯享网
递归sql(向下递归)如下:
with recursive p as (select t1.* from t_org_test t1 WHERE t1.id = 2 union all select t2.* from t_org_test t2 inner join p on t2.parent_id=p.id ) select id,name,parent_id from p
讯享网
结果如下:

- sql中
with xxxx as ()是对一个查询子句做别名,同时数据库会对该子句生成临时表; with recursive则是一个递归的查询子句,他会把查询出来的结果再次代入到查询子句中继续查询- p为自定义临时表名,最后一句select后跟的字段必须小于等于t1和t2中字段。
- 第二句where后面跟的是起始数据,第四句后面可以加where条件来判断终止条件
- 向上递归把
t2.parent_id=p.id改为t2.id=p.parent_id
现在有一个新的需求,求出所有组织机构下面乡村、城镇,并用逗号隔开。效果如下:

可以先在外层获取表所有数据,然后在递归的起始条件关联外层表id,达到与表id绑定唯一性的目的。把多行字符串用逗号隔开,用array_to_string(ARRAY(SELECT unnest(array_agg(name))),',') 和 string_agg(name,',') 都可以实现
二、oracle
语法:

讯享网查询语句 start with 起始条件 connect by prior 递归条件
1.向下递归(从子节点开始)

2.向下递归(从父节点开始)

3.向上递归(从子节点开始)

4.向上递归(从父节点开始)

这里由于父节点为191的有多个,且上层组织机构都为重庆电信,所以有重复数据
三、mysql
之所以把mysql放到最后,是因为mysql 8.0以下中没有实现递归的函数。
而mysql 8.0以上版本可以用和pgsql一样的with recursive实现递归
因此mysql8.0以下版本我们需要自己定义函数
原文地址:https://blog.csdn.net/lilizhou2008/article/details/
delimiter $$ drop function if exists get_child_list$$ create function get_child_list(in_id varchar(10)) returns varchar(1000) begin declare ids varchar(1000) default ''; declare tempids varchar(1000); set tempids = in_id; while tempids is not null do set ids = CONCAT_WS(',',ids,tempids); select GROUP_CONCAT(id) into tempids from t_org_test where FIND_IN_SET(parent_id,tempids)>0; end while; return ids; end $$ delimiter ;
然后调用函数

如果报错:
This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA in its de
在MySQL中创建函数时出现这种错误的解决方法:
set global log_bin_trust_function_creators=TRUE;
原文地址:https://blog.csdn.net/topasstem8/article/details//
https://www.cnblogs.com/kerrycode/p/7641835.html
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/29478.html