closed: An idea how to extract a forest with recursive SQL query
I need an idea, how to extract a forest of records using a recursive WITH .. RECURSIVE query in PostgreSql. The data structure is approximately looks like
create table rule ( id int primary key, obj_id int, start_time timestamp )
I need to extract all chains of rules for the every object, and recalculate the start_time for every i-th record by the way when i-th record functionally depends from the previous record. That's way I need a recursive query. I've got an idea how to extract a single list, it's looks like
with recursive rq (
select id, obj_id, start_time, id as prev from rule where id = :some_value
union all
select q.*
from (select id, obj_id, t, lead(r.id) over (order by start_time) as prev) q
join rq on rq.prev = q.id
)
and gives a sequence like
(root(A)) -> (rule1) -> (rule2) -> ...
but I need a a list for the every object:
(root(A)) -> (rule1) -> (rule2) -> ...
(root(B)) -> (rule1) -> (rule2) -> ...
...
(root(N)) -> (rule1) -> (rule2) -> ...
or:
object1|rule1
object1|rule2
...
object2|rule1
object2|rule2
...
and here I'm totally stuck. I've read a number of examples with trees and lists, but they usuall开发者_JS百科y operate with a single root record. Is there a possible way to do the trick with multiple roots? May be I need to extract the whole record set in the non-recursive part and then join it with itself recalculating the start_time field? Any other ideas?
Why not first select all roots and then use the with recursive option to fill the forest?
精彩评论