【问题标题】:Show the data based on Hierarchy [ Grand Parent -> Parent -> Child ]根据层次结构显示数据[祖父->父->子]
【发布时间】:2018-03-29 18:24:32
【问题描述】:

嗨,我想将数据显示为如下图所示的层次结构方式

这是我的数据库表结构

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

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

输出是

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

【问题讨论】:

  • 把最后一行改成LEFT JOIN ucode AS t3 ON t3.parent_id = t2.id
  • No Even 结果是错误的你可以检查问题中的结果..!我添加了那个结果
  • 所以你想显示树视图结构

标签: php mysql pdo


【解决方案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查看结果

【讨论】:

  • 但是在 sub quires 中编写 SQL 查询是非常糟糕我们必须在 join 中编写
【解决方案2】:

您需要使用 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

【讨论】:

  • 感谢您的回复……!你的结果很好,不是准确的答案,因为你的输出 secondary_id 结果应该出现在 primary_id 和 teritiary_Id 结果应该出现在 secondary_id 和 teritiary_Id 应该是 3 , 4, 6, 7 , 10, 11, 13, 14
  • 但这不是你的预期,I want to show data as Hierarchy way like this as show in below image ?
猜你喜欢
  • 1970-01-01
  • 2016-07-01
  • 1970-01-01
  • 2020-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-23
相关资源
最近更新 更多