- 论坛徽章:
- 0
|
用PHP语言+MySql数据库怎样做多级树型菜单?请各位多多指点!
这个问题前段smth有个贴子的想法很好,实际使用的时候这么设计表格,递归只有在更新树的时候使用一次就行,也很好写
发信人: gutentag (Bonjour & 刷·刷·刷刷·刷···), 信区: WebDev
标 题: Re: 有没有人写出一个递归算法显示论坛帖子的算法
发信站: BBS 水木清华站 (Tue Sep 14 13:45:30 2004), 站内
我也推荐这种保存树形结构相关的数据办法,虽然牺牲一点存储空间,
但是免去了递归查询时的消耗
比如,把concat(RootID, ..., 父父ID, 父ID, ID) 作为一个字段保存下来,
比如叫idstru,每个ID前面要补零使其长度相等,添加新数据的时候就把父记录的
idstru 与 新记录的ID 接起来
直接对它排序,得到的就是树形结构了
举个例子:
mysql>; select id, pid, name, idstru from rec order by idstru;
+----+------+----------+-----------------+
| id | pid | name | idstru |
+----+------+----------+-----------------+
| 2 | NULL | Bob | 002 |
| 1 | 2 | Durand | 002;001 |
| 4 | 1 | Lee | 002;001;004 |
| 10 | 4 | Goethe | 002;001;004;010 |
| 7 | 2 | Rau | 002;007 |
| 3 | NULL | Tom | 003 |
| 5 | 3 | Mike | 003;005 |
| 11 | 3 | Linda | 003;011 |
| 6 | 11 | Michelle | 003;011;006 |
+----+------+----------+-----------------+
mysql>; select concat(lpad('', (length(idstru)-3)/4*2, ' '),name) as name
->; from rec order by idstru;
+--------------+
| name |
+--------------+
| Bob |
| Durand |
| Lee |
| Goethe |
| Rau |
| Tom |
| Mike |
| Linda |
| Michelle |
+--------------+
需要删除的时候也很方便,如果要把所有子记录都一起删掉,
比如删掉 id = 1 的所有子记录
mysql>; delete rec from rec r1, rec r2
->; where r1.idstru like concat(r2.idstru, '%') and r2.id=1;
Query OK, 3 rows affected (0.02 sec)
【 在 losa (因为所以) 的大作中提到: 】
: 递归从数据库调数据效率太低了,不用
: 以前有讨论过(5859),先要从数据库的表结构入手,把一些生成树形需要
: 的数据作为字段存在表里,在增删改数据时即时计算好这些值
: ...................
--
O Lieb, o Liebe, Du segnest herrlich O Maedchen, Maedchen,
So golden schoen, Das frische Feld, Wie lieb ich dich!
Wie Morgenwolken Im Blütendampfe Wie blickt dein Auge!
Auf jenen Hoehn! Die volle Welt. Wie liebst du mich!
※ 修改:·gutentag 于 Sep 14 14:12:45 修改本文·[FROM: 166.111.38.*]
※ 来源:·BBS 水木清华站 smth.org·[FROM: 166.111.38.*] |
|