看來你加入了錯誤的領域
WITH RECURSIVE tree (CategoryID, CategoryParentID, CategoryName, category_tree, depth)
AS (
SELECT
CategoryID,
CategoryParentID,
CategoryName,
CategoryName AS category_tree,
0 AS depth
FROM categories
WHERE CategoryParentID IS NULL
UNION ALL
SELECT
c.CategoryID,
c.CategoryParentID,
c.CategoryName,
tree.category_tree || '/' || c.CategoryName AS category_tree,
depth+1 AS depth
FROM tree
JOIN categories c ON (tree.category_tree = c.CategoryParentID)
)
SELECT * FROM tree ORDER BY category_tree;
樣品。
-- create some test data
DROP SCHEMA tmp CASCADE;
CREATE SCHEMA tmp ;
SET search_path=tmp;
CREATE TABLE categories
-- (id SERIAL PRIMARY KEY
(categoryid SERIAL PRIMARY KEY
, categoryparentid bigint REFERENCES categories(categoryid)
, categoryname text
-- , status integer DEFAULT 0
-- , lang text
-- , ebaysiteid text
-- , country text
-- , tempid text
-- , leafcategory boolean
);
INSERT INTO categories(categoryid,categoryparentid) SELECT gs, 1+(gs/6)::integer
FROM generate_series(1,50) gs;
UPDATE categories SET categoryname = 'Name_' || categoryid::text;
UPDATE categories SET categoryparentid = NULL WHERE categoryparentid <= 0;
UPDATE categories SET categoryparentid = NULL WHERE categoryparentid >= categoryid;
WITH RECURSIVE tree (categoryid, categoryparentid, categoryname, category_tree, depth)
AS (
SELECT
categoryid
, categoryparentid
, categoryname
, categoryname AS category_tree
, 0 AS depth
FROM categories
WHERE categoryparentid IS NULL
UNION ALL
SELECT
c.categoryid
, c.categoryparentid
, c.categoryname
, tree.category_tree || '/' || c.categoryname AS category_tree
, depth+1 AS depth
FROM tree
JOIN categories c ON tree.categoryid = c.categoryparentid
)
SELECT * FROM tree ORDER BY category_tree;
編輯:其他( 「非功能」)符號遞歸似乎更好的工作:
WITH RECURSIVE tree AS (
SELECT
categoryparentid AS parent
, categoryid AS self
, categoryname AS treepath
, 0 AS depth
FROM categories
WHERE categoryparentid IS NULL
UNION ALL
SELECT
c.categoryparentid AS parent
, c.categoryid AS self
, t.treepath || '/' || c.categoryname AS treepath
, depth+1 AS depth
FROM categories c
JOIN tree t ON t.self = c.categoryparentid
)
SELECT * FROM tree ORDER BY parent,self
;
更新:在原來的查詢,就應該更換
WHERE CategoryParentID IS NULL
通過:
WHERE CategoryParentID = 0
或m aybe甚至:
WHERE COALESCE(CategoryParentID, 0) = 0
你有一種奇怪的方法來標記樹的根節點(通常一個會有根的NULL父指針)。查看我的更新。 – wildplasser 2012-08-06 21:18:15