您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

在mysql中建立树形结构_MySQL

2024/3/12 13:08:41发布25次查看
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表现在是什么情况了:
 很好,就是这个效果 现在可以按你的需求随便查询了: 比如: [sql]  select * from menu a where a.scort not like '%,1,%' order by a.scort     作者 lifaming15 bitscn.com
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product