以Postgresql为主,再聊聊资料库 递迴查询之找出循环参考

资料库的递迴查询,是很强大的功能,笔者以前使用 IBM DB2 时,就很喜欢使用递迴查询,因为可以帮助解决许多问题.在过往的问答中,也有一些使用递迴查询的例子.接着我们来看递迴查询中会出现的循环参考.以经典的递迴查询案例,组织层级来产生测试资料.为了简化起见,这里没有做FK.create table it200508 (  id integer not null primary key, mgr_id integer not null );insert into it200508select n     , (random() * 100)::int  from generate_series (1, 100) as g(n);  commit;接下来我们利用 PostgreSQL 的 Array , 还有其函数 any().就可以很方便的找出来是否有循环参考. with recursive cte (  id, mgr_id, depth, path, is_cycle) as (select i.id     , i.mgr_id     , 1     , array[i.id]     , false  from it200508 i union allselect i.id     , i.mgr_id     , c.depth + 1     , c.path || i.id     , i.id = any(path)   from it200508 i     , cte c where i.id = c.mgr_id   and not is_cycle)select depth     , path     , is_cycle  from cte where is_cycle;很巧的也有100组.鉴于本站设计的关係,程式码部分很窄,所以用贴图.

http://img2.58codes.com/2024/20050647B2TmqMBcQH.png

http://img2.58codes.com/2024/20050647qLSEMhdgGV.png


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章