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,%'

好了,更多用途慢慢去發現吧。

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM