Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

postgresql - Recursive CTE concatenate fields with parents from arbitrary point

How can I concatenate a list of parent items in a RECURSIVE CTE with PostgreSQL (version 10.2)?

For example, I have:

CREATE TABLE test (
    id SERIAL UNIQUE,
    parent integer references test(id),
    text text NOT NULL
);

with:

INSERT INTO test(parent, text) VALUES
(NULL, 'first'),
(1, 'second'),
(2, 'third'),
(3, 'fourth'),
(NULL, 'top'),
(5, 'middle'),
(6, 'bottom');

How do I get a tree with a particular item and all it's parents concatenated (or in an array) given it's id?

So far I have the following query to see what is being returned, but I can't seem to add the right WHERE clause to return the right value:

WITH RECURSIVE mytest(SRC, ID, Parent, Item, Tree, JOINED) AS (
  SELECT '1', id, parent, text, array[id], text FROM test
UNION ALL
  SELECT '2', test.id, test.parent, test.text as Item, NULL,
    concat(t.joined, '/', test.text)
  FROM mytest as t
  JOIN test ON t.id = test.parent
)
SELECT * FROM mytest;

This gives me the entire set but as soon as I add something like WHERE id = 1 I don't get the results I expect (I'm looking for a concatenated list of the item and parents).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In the top-down method the initial query should select only roots (items without parents), so the query returns each row only once:

with recursive top_down as (
    select id, parent, text
    from test
    where parent is null
union all
    select t.id, t.parent, concat_ws('/', r.text, t.text)
    from test t
    join top_down r on t.parent = r.id
)
select id, text
from top_down
where id = 4    -- input

If your goal is to find a specific item, the bottom-up approach is more efficient:

with recursive bottom_up as (
    select id, parent, text
    from test
    where id = 4    -- input
union all
    select r.id, t.parent, concat_ws('/', t.text, r.text)
    from test t
    join bottom_up r on r.parent = t.id
)
select id, text
from bottom_up
where parent is null

Remove final where conditions in both queries to see the difference.

Test it in rextester.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.6k users

...