Mysql笔记(二):递归分类层次查询

1.问题描述:

数据表结构同Mysql笔记(一),需求改为查找给定分类编码查找分类及其所有子类,包含子类的子类。

2.问题分析:

还是利用分类编码具有层次嵌套的特点,这一次需要按照org_code升序排列,目的是保障一个分类的子类一定出现在其后面。然后可以利用笔记(一)中相同的逻辑遍历每一个分类,关键点是需要不断扩充被查找的父类集合,然后利用find_in_set函数进行过滤。

(1)按org_code升序排列:

mysql> select org_code,parent_code from class order by org_code asc;
+------------------+--------------+
| org_code         | parent_code  |
+------------------+--------------+
| 0001             | NULL         |
| 00010001         | 0001         |
| 000100010001     | 00010001     |
| 000100010002     | 00010001     |
| 0001000100020001 | 000100010002 |
| 00010002         | 0001         |
| 00010003         | 0001         |
+------------------+--------------+
7 rows in set (0.00 sec)

(2)遍历排序后的数据,将待查寻父类的子类逐步添加到待查寻父类列表@p中:

mysql> select (case when org_code=@r or find_in_set(parent_code,@p) then org_code else null end) as child,(case when find_in_set(parent_code,@p) then @p:=concat(@p,',',org_code) else null end) as parents from (select org_code,parent_code from class order by org_code asc) as c,(select @r:='00010001',@p:='00010001') as t;
+------------------+-----------------------------------------------------+
| child            | parents                                             |
+------------------+-----------------------------------------------------+
| NULL             | NULL                                                |
| 00010001         | NULL                                                |
| 000100010001     | 00010001,000100010001                               |
| 000100010002     | 00010001,000100010001,000100010002                  |
| 0001000100020001 | 00010001,000100010001,000100010002,0001000100020001 |
| NULL             | NULL                                                |
| NULL             | NULL                                                |
+------------------+-----------------------------------------------------+
7 rows in set (0.00 sec)

(3)过滤查询结果,得到分类编号为00010001的分类及其子类的子类:

mysql> select child from (select (case when org_code=@r or find_in_set(parent_code,@p) then org_code else null end) as child,(case when find_in_set(parent_code,@p) then @p:=concat(@p,',',org_code) else null end) as parents from (select org_code,parent_code from class order by org_code asc) as c,(select @r:='00010001',@p:='00010001') as t) as m where child is not null;
+------------------+
| child            |
+------------------+
| 00010001         |
| 000100010001     |
| 000100010002     |
| 0001000100020001 |
+------------------+
4 rows in set (0.00 sec)

猜你喜欢

转载自www.cnblogs.com/ling-diary/p/10321459.html
今日推荐