php - 递归获取父母的名字
问题描述
我有一个看起来像这样的数据库:
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 吗?另外我应该如何循环它以获得我想要的输出?
解决方案
在 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
。
姓名 | 父母 :-------- | :-------------------- 史密斯 | 约翰逊 | 史密斯 斯宾塞 | 史密斯,约翰逊 公爵 | 史密斯,约翰逊,斯宾塞
推荐阅读
- sql - 在 Oracle 中解析多个 Json 数组元素
- python - Oracle数据库表的Django迁移错误
- javascript - 来自 Promise 的 Jest 模拟回调函数
- java - Spring boot JPA - 按实体集合排序
- ruby - 外部块中的动态方法可以在子块中访问吗?- Ruby 元编程
- amazon-web-services - 从 DynamoDB 的 Lambda 获取 JSON 可序列化输出时出错
- reactjs - 将具有状态的类组件转换为具有挂钩的功能组件
- unreal-engine4 - 虚幻引擎 (4.25.4) 不再打开项目
- google-apps-script - 提交 Google 表单后自动从 Google 表单响应中移动特定数据
- javascript - 使用 Apollo 客户端更新缓存数据 - ReactJS