简体   繁体   English

递归连接节点名称

[英]Concatenate node names recursively

I'm using Firebird 2.1 and I have the following hierarchical table:我使用的是 Firebird 2.1,我有以下层次结构表:

NodeID, ParentNodeID, Name

ParentNodeID = -1 for root nodes.对于根节点,ParentNodeID = -1。

For example:例如:

1, -1, Parent
2, 1, Child
3, 2, Child of child

I'm looking for a recursive query (or stored procedure) to output a concatenation the following way:我正在寻找递归查询(或存储过程)到 output 通过以下方式连接:

Parent
Parent - Child
Parent - Child - Child of child

Siblings should be sorted in alphabetic order.兄弟姐妹应按字母顺序排序。 How do I do this?我该怎么做呢?

You can do it with a stored procedure:您可以使用存储过程来做到这一点:

create procedure tree (root integer) returns (result varchar(1000)) as
  declare id integer;
  declare n varchar(30);
  declare childs varchar(1000);
begin
  for select NodeId, Name from t where ParentNodeId = :root order by Name into :id, :result do
   begin
    suspend;
    n = result;
    for select result from tree(:id) into :childs do
      begin
        result = n || ' - ' || childs;
        suspend;
      end
   end
end

https://dbfiddle.uk/_fY5xZS6 https://dbfiddle.uk/_fY5xZS6

In Firebird 2.1 and newer you could also use a recursive CTE.在 Firebird 2.1 和更新版本中,您还可以使用递归 CTE。

You can also solve this with a recursive CTE in Firebird 2.1:您还可以使用 Firebird 2.1 中的递归 CTE 解决此问题:

with recursive t as (
  select nodeid, name
  from relation
  where parentnodeid = -1
  union all
  select r.nodeid, t.name || ' - ' || r.name
  from t
  inner join relation r on r.parentnodeid = t.nodeid
)
select name
from t;

https://dbfiddle.uk/VBJ3B8Ka https://dbfiddle.uk/VBJ3B8Ka

If you need to order siblings by name, you can add an order by name to the top-level select.如果需要兄弟姐妹按姓名排序,可以在顶层select添加order by name排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM