简体   繁体   English

递归获取父母的名字

[英]Get names of parents recursively

I have a database that looks like this:我有一个看起来像这样的数据库:

CREATE TABLE Persons (
    id int,
    parentID int,
    name varchar(255)
);

INSERT INTO Persons (id, parentID, name) VALUES ('1', '0', 'smith');
INSERT INTO Persons (id, parentID, name) VALUES ('2', '1', 'johnson');
INSERT INTO Persons (id, parentID, name) VALUES ('3', '2', 'spencer');
INSERT INTO Persons (id, parentID, name) VALUES ('4', '3', 'duke');

I want to fetch the persons name, and name of their parent and put that in an array.我想获取人员姓名和他们父母的姓名并将其放入数组中。 Then loop through the array recursively to get an output that looks similar to this:然后递归地遍历数组,得到一个类似于下面的 output:

smith
johnson (smith)
spencer (johnson, smith)
duke (spencer, johnson, smith)

I want to do this in php and sql.我想在 php 和 sql 中执行此操作。

I am unsure of the sql query to use, should i use an recursive CTE?我不确定要使用 sql 查询,我应该使用递归 CTE 吗? Also how should i loop through it to get the output that i want?另外我应该如何遍历它以获得我想要的 output?

In MySQL 8.0, you can make use of a recursive common table expression:在 MySQL 8.0 中,您可以使用递归公用表表达式:

with recursive cte as (
    select 
        id,
        parentID,
        name, 
        cast('' as char(500)) parents
        from Persons
    where parentID = 0
    union all
    select 
        p.id,
        p.parentID,
        p.name,
        concat(c.parents, case when c.parents <> '' then ',' else '' end, c.name) parents
     from Persons p
     inner join cte c on c.id = p.parentID
)
select name, parents from cte

The query starts from the root of the tree ( where parentID = 0 ), and then walks through the hierarchy, concatenating the inheritance chain in new column parents .查询从树的根( where parentID = 0 )开始,然后遍历层次结构,在新列 parent 中连接parents链。

Demo on DB Fiddle : DB Fiddle 上的演示

name    | parents              
:------ | :--------------------
smith   |                      
johnson | smith                
spencer | smith,johnson        
duke    | smith,johnson,spencer

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

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