我正在寻找一个查询,我可以按组询问数据。例如:
table group
-uID-|-parentID-|-someData-
0 | 0 | foo
1 | 0 | bar
2 | 1 | foobar
3 | 2 | test
4 | 2 | demo
父ID指向父母组的uID。
例如:当我想要第3组时,我会回来"测试"只要。当我请求第1组时,结果将是:bar,foobar,test和demo。 所以我必须得到所有的行,其中parentID与我正在搜索的uID匹配。
如果我正在寻找第1组,将获得它以及所有子组2,3和4。
谢谢。
答案 0 :(得分:2)
在sqlite中,我们可以使用recursive CTE来解决此问题。
WITH RECURSIVE reccte AS
(
SELECT
uid as initialID,
uID,
parentID,
someData,
1 as depth
FROM table
WHERE uID = 1 /*starting point for recursive stuff*/
UNION ALL
/*Recursive statement*/
SELECT
reccte.initialID,
t1.uID,
t1.parentID,
someData,
depth + 1
FROM
reccte
INNER JOIN table as t1 ON
recCTE.uID = t1.parentID /*joining up the parent*/
WHERE depth < 15 /*keep from endless loops*/
)
/*Select all the someData's that resulted from the recursive lookup*/
SELECT someData FROM recCTE;