图中的循环导致 CTE 中的无限循环。
在 Postgres 中处理它们很简单。
从 8.0 开始,MySQL 也允许 CTE。我如何检测 MySQL CTE 中的循环和无限循环?
目标不是在 1000 次或任何迭代次数后中断查询,而是在代码中实际处理它(例如,通过在数组中收集已访问节点的列表并设置不等式条件以避免循环)。
或者是否有任何“内置”选项来处理这个问题,比如cycle COLNAME
在 Postgres CTE 中?
我当前的代码看起来像这样
with recursive circle as (
select friend2, name2, 0 as depth from my_view1 where friend1 = 1
union
select m.friend2, m.name2, c.depth+1 from my_view1 m
inner join circle c on c.friend2 = m.friend1)
select * from circle where circle.depth < 2;
可以使用以下方法创建基础表:
create table people (person_id integer primary key, name varchar(20) not null);
insert into people (person_id, name) values (1, 'tom'), (2, 'dick'), (3, 'harry'), (4, 'susan'), (5, 'mary'), (6, 'jill');
create table friends (friend1 integer references people (person_id), friend2 integer references people (person_id), primary key (friend1, friend2));
insert into friends (friend1, friend2) values (1,2), (2, 3), (3, 4), (5, 6);
insert into friends (friend1, friend2) values (2,1), (3,2), (4,3), (6,5);
create view my_view1 as select f.friend1, p.name as name1, f.friend2, p1.name as name2 from friends f join people p on p.person_id = f.friend1 join people p1 on p1.person_id = f.friend2 ;
在这种情况下,CTE 中的 UNION DISTINCT 足以防止循环:
小提琴
如果您需要特定用户或用户列表的友谊数据,请编辑/取消注释 CTE 基本查询中的条件。
如果您需要将此查询用作视图
CREATE VIEW collect_friends AS
,请在开头添加。