首页 > 数据库 > mysql教程 > 在mysql中建立树形结构_MySQL

在mysql中建立树形结构_MySQL

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
发布: 2016-06-01 13:41:57
原创
1589 人浏览过

bitsCN.com 在mysql中建立树形结构 这个不是什么新东西了,网上有很多方法,我也尝试了其中好的方法,都不尽人意,这是我最后我推荐的方法,共享一下,大家一起讨论,当然难如高手法眼,呵呵。我就直接贴代码了,有问题就联系我。 mysql中要有树形结构我认为表中应该有如写字段: 举例菜单表menu:   [sql]  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: [sql]  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  插入数据:[sql]  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);     执行存储过程:[sql]  call genNode_menu;  我们看一看menu表现在是什么情况了:
在mysql中建立树形结构_MySQL 很好,就是这个效果 现在可以按你的需求随便查询了: 比如: [sql]  select * from menu a where a.scort not like '%,1,%' order by a.scort     作者 lifaming15 bitsCN.com

相关标签:
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
mysql 升级后无法重启mysql服务的问题
来自于 1970-01-01 08:00:00
0
0
0
linux安装mysql报错
来自于 1970-01-01 08:00:00
0
0
0
MySQL停止进程
来自于 1970-01-01 08:00:00
0
0
0
phpstudy不能启动mysql?
来自于 1970-01-01 08:00:00
0
0
0
环境中mysql
来自于 1970-01-01 08:00:00
0
0
0
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板