栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Parent child mysql

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Parent child mysql

您可以尝试以下方法:

select t.*,       (case when t4.parent_id is not NULL then 5  when t4.id is not null then 4  when t3.id is not null then 3  when t2.id is not null then 2  when t1.id is not null then 1  else 0        end) as levelfrom t left outer join     t t1     on t.parent_id = t1.id left outer join     t t2     on t1.parent_id = t2.id left outer join     t t3     on t2.parent_id = t3.id left outer join     t t4     on t3.parent_id = t4.idorder by coalesce(t4.parent_id, t4.id, t3.id, t2.id, t1.id, t.id),         coalesce(t4.id, t3.id, t2.id, t1.id, t.id),         coalesce(t3.id, t2.id, t1.id, t.id),         coalesce(t1.id, t.id),         t.id

如果层次结构是有限的,则不需要递归查询。

order by子句是棘手的部分。它只是从最高级别开始按层次结构的级别进行排序。

该版本的原始版本适用于问题中的数据。更广泛的测试发现它并不总是有效。我相信此版本始终有效。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/373503.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号