SQLite中的深度优先搜索

SQLite中的深度优先搜索,sqlite,infinite-loop,Sqlite,Infinite Loop,我正在尝试在SQLite中实现深度优先搜索: 我有下表: CREATE TABLE table1(id INTEGER PRIMARY KEY ,id_parrent INTEGER ,id_child INTEGER ); INSERT INTO table1(id_parrent,id_child) VALUES('1','4'); INSERT INTO table1(id_parrent,id_child) VALUES('1','1'); INSERT INTO table1(id_

我正在尝试在SQLite中实现深度优先搜索: 我有下表:

CREATE TABLE table1(id INTEGER PRIMARY KEY ,id_parrent INTEGER ,id_child INTEGER );

INSERT INTO table1(id_parrent,id_child) VALUES('1','4');
INSERT INTO table1(id_parrent,id_child) VALUES('1','1');
INSERT INTO table1(id_parrent,id_child) VALUES('1','3');
INSERT INTO table1(id_parrent,id_child) VALUES('1','2');
INSERT INTO table1(id_parrent,id_child) VALUES('2','8');
INSERT INTO table1(id_parrent,id_child) VALUES('2','7');
INSERT INTO table1(id_parrent,id_child) VALUES('2','3');
INSERT INTO table1(id_parrent,id_child) VALUES('2','6');
INSERT INTO table1(id_parrent,id_child) VALUES('2','10');
INSERT INTO table1(id_parrent,id_child) VALUES('2','5');
INSERT INTO table1(id_parrent,id_child) VALUES('2','9');
INSERT INTO table1(id_parrent,id_child) VALUES('2','2');    
我尝试使用以下查询进行深度优先搜索:

WITH RECURSIVE
 under_parrent(id_child,level) AS (
  VALUES('1','0')
UNION ALL
SELECT table1.id_child, under_parrent.level+1
  FROM table1,under_parrent 
  WHERE table1.id_parrent = under_parrent.id_child
 ORDER BY 2 DESC
 )
SELECT id_child FROM under_parrent;
我的问题是结果是无限循环的,如图所示:

您的第二条记录将
1
连接到自身;查询正确地报告了这个无限循环

通常,通过使用
UNION
而不是
UNION ALL
来避免重复,但在这种情况下,这不起作用,因为
级别
值不同。 您必须过滤掉
WHERE
table1.id\u parrent table1.id\u child
)中的那些循环,但如果存在较大的循环(例如1→ 2.→ 1)