php mysql 树,php / Mysql最佳树形结构

I have to build a tree that will contain about 300 nodes inside it. The tree has no depth limitations. So it can have 3 or 15 levels. Each node can have an unlimited number of children.

The priority is to get a complete tree / subtree the faster as possible, but I also need to add nodes or move nodes sometimes but not that often.

I want to know the best way to store the tree in the database and the best way to retrieve the data, if possible, in php.

解决方案

You can use a Nested Set Model as it yields very efficient queries. Check out Managing Hierarchical Data in MySQL and read the section called Nested Set Model.

If you're using an ORM like Doctrine, it includes nested set capabilities.

It can be difficult for some to grasp the nested set concepts of left and right. I have found that using those numbers as an analogy for the line numbers of open/close tags in an XML document, folks find it easier to grasp.

For instance, take the data example from the MySQL link above:

+-------------+----------------------+-----+-----+

| category_id | name | lft | rgt |

+-------------+----------------------+-----+-----+

| 1 | ELECTRONICS | 1 | 20 |

| 2 | TELEVISIONS | 2 | 9 |

| 3 | TUBE | 3 | 4 |

| 4 | LCD | 5 | 6 |

| 5 | PLASMA | 7 | 8 |

| 6 | PORTABLE ELECTRONICS | 10 | 19 |

| 7 | MP3 PLAYERS | 11 | 14 |

| 8 | FLASH | 12 | 13 |

| 9 | CD PLAYERS | 15 | 16 |

| 10 | 2 WAY RADIOS | 17 | 18 |

+-------------+----------------------+-----+-----+

If you take the lft, rgt fields and use them as line numbers for an XML document, you get:

1.

2.

3.

4.

5.

6.

7.

8.

9.

10.

11.

12.

13.

14.

15.

16.

17. <2 way radios>

18. 2 way radios>

19.

20.

Seeing it this way can make it much easier for some to visualize the resulting nested set hierarchy. It also makes it clearer why this approach improves efficiency as it makes it possible to select entire nodes without the need for multiple queries or joins.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值