SQL 递归查询和输出
SQL Recursive Query and Output
使用以下 SQL 语句创建 table 并插入值:
create table tb(id int , pid int , name nvarchar(10))
insert into tb values( 1 , null , 'A')
insert into tb values( 2 , null , 'B')
insert into tb values( 3 , null , 'C')
insert into tb values( 4 , 1 , 'D')
insert into tb values( 5 , 1 , 'E')
insert into tb values( 6 , 2 , 'F')
insert into tb values( 7 , 3 , 'G')
insert into tb values( 8 , 4 , 'H')
insert into tb values( 9 , 5 , 'I')
我希望最终输出显示这棵树从根到叶的每一行,如下所示:
A-D-H
A-E-I
B-F
C-G
有人知道如何编写 SQL 程序来执行此操作吗?谢谢。
如果你使用的是SQL服务器那么你可以使用递归查询来解决。在 Oracle 和 PostgreSQL.
中可以使用类似的方法
with rcte as
(
select t1.id, t1.pid, cast(t1.name as nvarchar(100)) name
from tb t1
where not exists (select 1 from tb t2 where t2.pid = t1.id)
union all
select tb.id, tb.pid, cast(concat(tb.name, '-', rcte.name) as nvarchar(100)) name
from rcte
join tb on rcte.pid = tb.id
)
select name
from rcte
where rcte.pid is null
它先找到叶节点,然后遍历到根。
使用以下 SQL 语句创建 table 并插入值:
create table tb(id int , pid int , name nvarchar(10))
insert into tb values( 1 , null , 'A')
insert into tb values( 2 , null , 'B')
insert into tb values( 3 , null , 'C')
insert into tb values( 4 , 1 , 'D')
insert into tb values( 5 , 1 , 'E')
insert into tb values( 6 , 2 , 'F')
insert into tb values( 7 , 3 , 'G')
insert into tb values( 8 , 4 , 'H')
insert into tb values( 9 , 5 , 'I')
我希望最终输出显示这棵树从根到叶的每一行,如下所示:
A-D-H
A-E-I
B-F
C-G
有人知道如何编写 SQL 程序来执行此操作吗?谢谢。
如果你使用的是SQL服务器那么你可以使用递归查询来解决。在 Oracle 和 PostgreSQL.
中可以使用类似的方法with rcte as
(
select t1.id, t1.pid, cast(t1.name as nvarchar(100)) name
from tb t1
where not exists (select 1 from tb t2 where t2.pid = t1.id)
union all
select tb.id, tb.pid, cast(concat(tb.name, '-', rcte.name) as nvarchar(100)) name
from rcte
join tb on rcte.pid = tb.id
)
select name
from rcte
where rcte.pid is null
它先找到叶节点,然后遍历到根。