mysql 层次数据_MySQL层次结构数据提取

bd96500e110b49cbb3cd949968f18be7.png

I've been struggling for about 2 hours on one query now. Help? :(

I have a table like this:

id name lft rgt

35 Top level board 1 16

37 2nd level board 3 6 15

38 2nd level board 2 4 5

39 2nd level board 1 2 3

40 3rd level board 1 13 14

41 3rd level board 2 9 12

42 3rd level board 3 7 8

43 4th level board 1 10 11

It is stored in the structure recommended in this tutorial. What I want to do is select a forum board and all sub forums ONE level below the selected forum board (no lower). Ideally, the query would get the selected forum's level while only being passed the board's ID, then it would select that forum, and all it's immediate children.

So, I would hopefully end up with:

id name lft rgt

35 Top level board 1 16

37 2nd level board 3 6 15

38 2nd level board 2 4 5

39 2nd level board 1 2 3

Or

id name lft rgt

37 2nd level board 3 6 15

40 3rd level board 1 13 14

41 3rd level board 2 9 12

42 3rd level board 3 7 8

The top rows here are the parent forums, the others sub forums. Also, I'd like something where a depth value is given, where the depth is relative to the selected parent form. For example, taking the last table as some working data, we would have:

id name lft rgt depth

37 2nd level board 3 6 15 0

40 3rd level board 1 13 14 1

41 3rd level board 2 9 12 1

42 3rd level board 3 7 8 1

Or

id name lft rgt depth

35 Top level board 1 16 0

37 2nd level board 3 6 15 1

38 2nd level board 2 4 5 1

39 2nd level board 1 2 3 1

I hope you get my drift here.

Can anyone help with this? It's really getting me annoyed now :(

James

解决方案

One more thing to consider is that relational databases really are not the most optimal and natural way to store hierarchical data. A structure like you have here - a binary tree, essentially - would be much easier to represent with an XML blob that you can persist, or store as an object in an object-oriented database.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值