MySQL数据中分级分组显示数据

  前面已经有了SqlServer数据分级分组显示数据了。今天又来做一个MySQL数据库中的分级分组显示,SqlServer中用到了递归,这里为了简单就直接把根的数据显示为0 ,而不用递归了。

 在MySQL数据库中创建数据表:

CREATE TABLE `categories` (
    `id`  int(11) NOT NULL AUTO_INCREMENT COMMENT '分类id' ,
    `name`  varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '分类名称' ,
    `parent`  int(11) NOT NULL COMMENT '分类的父id' ,
    `path`  varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '分类的继承路径' ,
    `is_leaf`  tinyint(1) NOT NULL DEFAULT 0 COMMENT '是否叶节点' ,
    PRIMARY KEY (`id`),
    INDEX `parent` (`parent`) USING BTREE ,
    INDEX `path` (`path`) USING BTREE ,
    INDEX `path,is_leaf` (`path`, `is_leaf`) USING BTREE
)
ENGINE=InnoDB

表已经建好了,现在来插入测试数据:

insert into categories(`name`,parent,path,is_leaf) values('',0,'1',0);
insert into categories(`name`,parent,path,is_leaf) values('分类1',1,'1,2',0);
insert into categories(`name`,parent,path,is_leaf) values('分类2',1,'1,3',0);
insert into categories(`name`,parent,path,is_leaf) values('分类1-分类1',2,'1,2,4',1);
insert into categories(`name`,parent,path,is_leaf) values('分类2-分类1',2,'1,3,5',1);
insert into categories(`name`,parent,path,is_leaf) values('分类2-分类2',2,'1,3,6',1);
insert into categories(`name`,parent,path,is_leaf) values('分类1-分类2',2,'1,2,7',1);
insert into categories(`name`,parent,path,is_leaf) values('分类1-分类1-分类1',3,'1,2,4,8',1);
insert into categories(`name`,parent,path,is_leaf) values('分类2-分类1-分类2',3,'1,3,5,9',1);
insert into categories(`name`,parent,path,is_leaf) values('分类2-分类2-分类1',3,'1,3,6,10',1);
insert into categories(`name`,parent,path,is_leaf) values('分类1-分类2-分类2',3,'1,2,7,11',1);
insert into categories(`name`,parent,path,is_leaf) values('分类1-分类1-分类2',3,'1,2,4,12',1);
insert into categories(`name`,parent,path,is_leaf) values('分类2-分类1-分类1',3,'1,3,5,13',1);
insert into categories(`name`,parent,path,is_leaf) values('分类2-分类2-分类2',3,'1,3,6,14',1);
insert into categories(`name`,parent,path,is_leaf) values('分类1-分类2-分类1',3,'1,2,7,15',1);

查询得到的结果是:

select * from categories  ;

接下来开始我们的分级分组显示数据了SQL语句

select  id, case parent when 0 then `name` else '' end as '第一级栏目',
        case parent when 1 then `name` else '' end as '第二级栏目',
        case parent when 2 then `name` else '' end as '第三级栏目',
        case parent when 3 then `name` else '' end as '第四级栏目'
   from   categories  GROUP BY  path


结果是如下图:

这就是我们想要的结果。

其实他们说这个表结构可以实现无限分类的。我们可以这样查询。

SELECT * FROM categories WHERE path LIKE '%5%' 
select * from categories  where  path like '1,3,5,%'

好了,更多用途慢慢去发现吧。

原文地址:https://www.cnblogs.com/annabook/p/3807542.html