mysql递归查询-案例(2)
2022/9/18 2:16:24
本文主要是介绍mysql递归查询-案例(2),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
表数据如下
+--------+----------+------------+
| cat_id | name | parent_cid |
+--------+----------+------------+
| 12 | 美妆 | 0 |
| 4 | 服装 | 0 |
| 5 | 女装 | 4 |
| 6 | 男装 | 4 |
| 7 | 童装 | 4 |
| 19 | 美容美体 | 12 |
| 18 | 彩妆 | 12 |
| 13 | 护肤 | 12 |
| 15 | 护肤套装 | 13 |
| 40 | 防晒 | 13 |
| 39 | 卸妆 | 13 |
| 38 | 润唇膏 | 13 |
| 17 | 乳液面霜 | 13 |
| 16 | 面膜 | 13 |
| 14 | 化妆水 | 13 |
+--------+----------+------------+
1. 我们需要查询出"服装"分类下的所有子分类
with recursive type_cte as ( select * from t_category where cat_id = 4 union all select t.* from t_category t inner join type_cte type_cte2 on t.parent_cid = type_cte2.cat_id ) select cat_id, name, parent_cid from type_cte
返回:
+--------+------+------------+ | cat_id | name | parent_cid | +--------+------+------------+ | 4 | 服装 | 0 | | 5 | 女装 | 4 | | 6 | 男装 | 4 | | 7 | 童装 | 4 | +--------+------+------------+
2. 查询出所有“美妆”分类下的所有子分类,并且分类名称带上上级分类的名称
with recursive type_cte as ( select cat_id,name,parent_cid from t_category where cat_id = 12 union all select t.cat_id,concat(type_cte2.name,'>',t.name),t.parent_cid from t_category t inner join type_cte type_cte2 on t.parent_cid = type_cte2.cat_id ) select cat_id, name, parent_cid from type_cte;
返回:
+--------+------------------------+------------+ | cat_id | name | parent_cid | +--------+------------------------+------------+ | 12 | 美妆 | 0 | | 13 | 美妆>护肤 | 12 | | 18 | 美妆>彩妆 | 12 | | 19 | 美妆>美容美体 | 12 | | 14 | 美妆>护肤>化妆水 | 13 | | 15 | 美妆>护肤>护肤套装 | 13 | | 16 | 美妆>护肤>面膜 | 13 | | 17 | 美妆>护肤>乳液面霜 | 13 | | 35 | 美妆>护肤>洁面 | 13 | | 36 | 美妆>护肤>精华 | 13 | | 37 | 美妆>护肤>眼霜 | 13 | | 38 | 美妆>护肤>润唇膏 | 13 | | 39 | 美妆>护肤>卸妆 | 13 | | 40 | 美妆>护肤>防晒 | 13 | +--------+------------------------+------------+
3. 查询分类的所有父级分类
根据第二个问题的sql做一下调整即可
with recursive type_cte as ( select cat_id,name,parent_cid from t_category where cat_id = 40 union all select t.cat_id,concat(type_cte2.name,'>',t.name),t.parent_cid from t_category t inner join type_cte type_cte2 on t.cat_id = type_cte2.parent_cid ) select cat_id, name, parent_cid from type_cte;
返回:
+--------+----------------+------------+ | cat_id | name | parent_cid | +--------+----------------+------------+ | 40 | 防晒 | 13 | | 13 | 防晒>护肤 | 12 | | 12 | 防晒>护肤>美妆 | 0 | +--------+----------------+------------+
这篇关于mysql递归查询-案例(2)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-04-01JPA不识别MySQL的枚举类型
- 2024-03-30mysql数据库表卡死解决方法
- 2024-03-15MySQL多数据源笔记5-ShardingJDBC实战
- 2024-03-11natural join mysql
- 2024-03-11关于VS2017,VS2015 中利用 EF使用Mysql 不显示数据源问题解决方案
- 2024-02-26mysql 阿里云xb后缀备份文件恢复-icode9专业技术文章分享
- 2024-02-22docker mysql 5.7
- 2024-02-18从 20 多套 MySQL 到 1 套 TiDB丨骏伯网络综合运营管理平台应用实践
- 2024-02-07mysql 外键索引入门介绍,为什么工作中很少有人使用?
- 2024-01-19你真的了解MySQL日期函数吗?