欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  数据库

关于mysql中数据存储复合树形结构,查询时结果按树形结构输出_MySQL

程序员文章站 2022-06-15 20:17:23
...
bitsCN.com

1、主要思想:根据已有数据,规则性的造数据

select * FROM(
select lId,strName,lId as lParentId,-1 as orderIdx from tbClassify WHERE lParentId = 0
UNION ALL
(select t1.* from tbClassify t1 join
(select lId from tbClassify where lParentId=0 order by orderIdx) t2 on
t1.lParentId = t2.lId
where 1=1 order by t1.lParentId,t1.orderIdx)
) tbLast where 1=1 GROUP BY tbLast.lParentId,tbLast.lId ORDER BY tbLast.lParentId,tbLast.orderIdx
;

上面的排序有问题,最后成型:

select lId FROM(
select lId,orderIdx as pIdx,-1 as sIdx from tbClassify WHERE lParentId = 0
UNION ALL
(select a.lId,b.orderIdx pIdx,a.orderIdx sIdx from tbClassify a left JOIN tbClassify b on (a.lParentId = b.lId ) where a.lParentId != 0)
)
tbLast ORDER BY tbLast.pIdx,tbLast.sIdx
;

该方法缺陷:前提必须知道树形结构共有几层,不带有通用型,当前方法只适用于两层树形结构,重点是提供了一种解决问题的思路:根据已有数据造数据

bitsCN.com
相关标签: mysql