前言

本文使用Mysql8.0的特新实现递归查询,文中给出了详细的实例代码,下面话不多说了,来一起看看详细的介绍吧

Mysql8.0递归查询用法

表数据如下

+--------+----------+------------+
| 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_cidfrom type_cte

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_cidfrom type_cte;

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_cidfrom type_cte;

总结

更多相关文章

  1. MySQL系列多表连接查询92及99语法示例详解教程
  2. Andorid Dialog 示例【慢慢更新】
  3. Android(安卓)PureMVC
  4. Ubunu下搭建android NDK环境
  5. 自定义SeekBar主题
  6. android SQLite数据库基本操作示例
  7. android draw bitmap 示例代码
  8. Android启动时启动Activity 的定义的位置
  9. Android适配器之------BaseAdapter(例子)

随机推荐

  1. Java记录 -88- 利用反射机制调用对象的私
  2. java客户端调用 https 的webservice
  3. Java基础小常识(4)
  4. 「小程序JAVA实战」小程序头像图片上传(中
  5. 一个简单的java网络爬虫(spider)
  6. 如何修改代码,使其仅打印单元格E和F?
  7. 今年暑假不AC (JAVA)
  8. java lang涉及抽象类的NullPointerExcept
  9. 在命令行下编译单个带包名的java类的方法
  10. eclipse中java工程转web工程