递归获取父母的姓名

时间:2019-11-11 20:00:52

标签: php mysql sql arrays common-table-expression

我有一个看起来像这样的数据库:

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');

我想获取人员名称和其父母的姓名,并将其放入数组中。然后递归地遍历数组以获得类似于以下内容的输出:

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

我想在php和sql中做到这一点。

我不确定要使用的sql查询,我应该使用递归CTE吗? 另外我应该如何遍历它以获得我想要的输出?

1 个答案:

答案 0 :(得分:2)

在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

查询从树的根(where parentID = 0)开始,然后遍历层次结构,将继承链连接到新列parents中。

Demo on DB Fiddle

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