mysql建立树形结构_在mysql中建立树形结构

本文介绍了一种在MySQL中实现树形结构的方法。通过创建包含特定字段的表,并使用存储过程来更新节点层级和路径,使得查询树形结构变得简单。文章提供了具体的SQL语句和示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这个不是什么新东西了,网上有很多方法,我也尝试了其中好的方法,都不尽人意,这是我最后我推荐的方法,共享一下,大家一起讨论,当然难如高手法眼,呵呵。我就直接贴代码了,有问题就联系我。

mysql中要有树形结构我认为表中应该有如写字段:

举例菜单表menu:

create table menu

(

id int not null auto_increment,

pid int,

name varchar(100) not null,

nlevel int,

scort varchar(8000),

primary key (id)

)

type = InnoDB;

alter table menu add constraint FK_Reference_67 foreign key (pid)

references menu (id) on delete restrict on update restrict

创建存储过程genNode_menu:

BEGIN

DECLARE Level int ;

Set Level=0 ;

update menu a inner join (SELECT id,Level,concat(',',ID,',') scort FROM menu WHERE pid is null) b on a.id=b.id

set a.nlevel=b.level,a.scort=b.scort;

WHILE FOUND_ROWS()>0 DO

SET Level=Level+1;

update menu a inner join (

SELECT ID,Level,scort FROM menu

WHERE nLevel=Level-1) b on a.pid=b.id

set a.nlevel=b.level,a.scort=concat(b.sCort,a.ID,',');

END WHILE;

END插入数据:

INSERT INTO menu VALUES ('1', null, '菜单1', null, null);

INSERT INTO menu VALUES ('2', '1', '菜单1-1', null, null);

INSERT INTO menu VALUES ('3', null, '菜单2', null, null);

INSERT INTO menu VALUES ('4', '3', '菜单2-1', null, null);

INSERT INTO menu VALUES ('5', '4', '菜单2-1-1', null, null);

执行存储过程:

call genNode_menu;我们看一看menu表现在是什么情况了:

1339658784_1793.jpg

很好,就是这个效果

现在可以按你的需求随便查询了:

比如:

select * from menu a where a.scort not like '%,1,%' order by a.scort

分享到:

18e900b8666ce6f233d25ec02f95ee59.png

72dd548719f0ace4d5f9bca64e1d7715.png

2012-06-14 15:23

浏览 151

评论

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值