mysql用一句sql语言表述出三级的父子关系

时间:2022-01-29 11:36:55

最近在工作上遇到的这个问题,本来想用函数解决但是不允许,所以用了该方法,有点笨,只适合三级以下的比较少的父子关系,不推荐使用层级多的人使用哦。

表名随便起的,就叫ppt1吧。

表结构中含有:id,parent_id,parent_level表述本级的id,父级id,默认为0,以及本级的层数,0表示没有父级,1表示一层,2表示两层。

首先查询出0层的数据:

SELECT *,0 as parent1,0 as parent2, id as parent3 from ppt1 where parent_level=0

然后查询出1层的数据:

SELECT t2.*,0 as parent1,t2.id as parent2,t1.id as parent3
from ppt1 as t1 
INNER JOIN ppt1 as t2 
ON t1.id=t2.parent_id where t2.parent_level=1

使用的是内连接方式,将数据显示出来。下面接着查询出2层的数据:

SELECT t3.*,t3.id as parent1,t2.id as parent2,t1.id as parent3
from(ppt1 as t1 INNER JOIN ppt1 as t2 ON t1.id=t2.parent_id)
INNER JOIN ppt1 as t3
on t2.id=t3.parent_id WHERE t3.parent_level=2

将三个表的数据全部加载在一起之后,对parent1,parent2,parent3的数据进行排序即可,parent1代表的是父级的父级也就是爷爷级的id,parent2代表的是父级的id,parent3代表的是子集的id,

SELECT *,CONCAT(parent3,'.',parent2,'.',parent1) as xulie from (

SELECT *,0 as parent1,0 as parent2, id as parent3 from ppt1 where parent_level=0

UNION

SELECT t2.*,0 as parent1,t2.id as parent2,t1.id as parent3
from ppt1 as t1 
INNER JOIN ppt1 as t2 
ON t1.id=t2.parent_id where t2.parent_level=1

UNION

SELECT t3.*,t3.id as parent1,t2.id as parent2,t1.id as parent3
from(ppt1 as t1 INNER JOIN ppt1 as t2 ON t1.id=t2.parent_id)
INNER JOIN ppt1 as t3
on t2.id=t3.parent_id WHERE t3.parent_level=2
) abc ORDER BY parent3 DESC,parent2 ASC,parent1 ASC
排序方法有两种,一种是按照上面的方法进行排序,还有一种是将三个数据都整合到xulie一个列中,然后将xulie进行排序