资料库的递迴查询,是很强大的功能,笔者以前使用 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组.鉴于本站设计的关係,程式码部分很窄,所以用贴图.

