您好,我想将数据显示为层次结构,如下图所示
这是我的数据库表结构
这是我用过的查询但不是我想要的完美结果
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
,输出
这不是我需要的
还有一种我试过的方式
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
,输出
答案 0 :(得分:1)
这是查询
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获取结果
答案 1 :(得分:0)
您需要使用INNER JOIN
代替LEFT JOIN并限制查询以仅返回有子女使用的父母WHERE
我的查询不会跳过您想要显示的列值,但您可以在循环查询结果时执行PHP。
SELECT
t1.parent_id AS primary_Id,
t2.parent_id AS secondary_Id,
t3.parent_id AS teritiary_Id
FROM ucode AS t1
INNER JOIN ucode AS t2 ON (t2.parent_id = t1.id )
INNER JOIN ucode AS t3 ON (t3.parent_id = t2.id )
where t1.parent_id = 0
<强> Demo 强>