php - 根据层次结构显示数据 [祖父 -> 父 -> 子]

标签 php mysql pdo

您好,我想以如下图所示的层次结构方式显示数据

enter image description here

这是我的数据库表结构

enter image description here

这是我使用过的查询,但它不是我想要的完美结果

SELECT 

t1.parent_id AS primary_Id,
t2.parent_id AS secondary_Id,
t3.parent_id AS teritiary_Id

FROM ucode AS t1
LEFT JOIN ucode AS t2 ON t2.parent_id = t1.id
LEFT JOIN ucode AS t3 ON t3.parent_id = t2.parent_id

输出是

enter image description here

这不是我需要的

还有一种我尝试过的方法

SELECT 
    
    t1.parent_id AS primary_Id,
    t2.parent_id AS secondary_Id,
    t3.parent_id AS teritiary_Id
    
    FROM ucode AS t1
    LEFT JOIN ucode AS t2 ON t2.parent_id = t1.id
    LEFT JOIN ucode AS t3 ON t3.parent_id = t2.id

输出是

enter image description here

你能给我一个正确的解决方案吗..

最佳答案

这里是查询

Select gparent, parent, id from ucode as c_tbl,
(SELECT gparent, id as parent from ucode as p_tbl,
(SELECT id as gparent FROM `ucode` WHERE parent_id = 0) as gp_tbl
where p_tbl.parent_id = gp_tbl.gparent) parent_tbl
where c_tbl.parent_id = parent_tbl.parent;

点击Demo结果

关于php - 根据层次结构显示数据 [祖父 -> 父 -> 子],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49551923/

相关文章:

mysql - MySQL 服务器是否允许使用 Python 脚本?

php - PDO::rowCount 与 COUNT(*)

phpmyadmin 和 mysql pdo lastInsertId()

php - Laravel Eloquent : How to select friend user model?

php - 如何从 mysql 列中减去最高值和最低值得到平均值

mysql - 无法备份数据库

php - 使用 PDO 从 MySQL 获取数据

php - 将此函数转换为 PDO

PHP规范化多维数组

mysql - 有什么理由担心表格中的列顺序吗?