我有一个具有此结构的sqlite数据库
create table categories
( CategoryID integer not null primary key
, CategoryName text not null
, CategoryParentID integer null
,FOREIGN KEY (CategoryParentID) REFERENCES categories(CategoryID)
);
根据父ID,我想拥有n级的所有后代(作为树),但我不知道该怎么做。 真的很感谢你的帮助。
我已经有类似的东西,但我不知道在哪里放置父ID条件来开始搜索
WITH RECURSIVE cte_categories (categorias.CategoryID, categorias.CategoryName, categorias.CategoryParentID, depth) AS (
SELECT categorias.CategoryID, categorias.CategoryName, categorias.CategoryParentID, 1
FROM categorias
WHERE categorias.CategoryParentID IS NULL
UNION ALL
SELECT c.CategoryID, c.CategoryName, c.CategoryParentID, r.depth + 1
FROM categories AS c
INNER JOIN cte_categories AS r ON (c.CategoryParentID = r.CategoryID)
)
SELECT CategoryName, depth, CategoryParentID
FROM cte_categories ORDER BY depth, CategoryName;