Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show the data based on Hierarchy [ Grand Parent -> Parent -> Child ]

Tags:

php

mysql

pdo

Hi I want to show data as Hierarchy way like this as show in below image

enter image description here

and here is my database table structure

enter image description here

and here is the query i have used but its not the perfect result i want

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

and the output is

enter image description here

this is not i need

and one more way i tried

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

and the output is

enter image description here

can you give me the proper solution for this..

like image 225
Gss Venkatesh Avatar asked Nov 08 '22 08:11

Gss Venkatesh


1 Answers

Here is the query

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;

Click Demo for the result

like image 168
Gss Venkatesh Avatar answered Nov 14 '22 21:11

Gss Venkatesh