mysql递归出所有父目录_使用单个查询(递归查询)在mysql表中查找所有父级

博客内容介绍了如何在MySQL中使用单个查询递归地找出所有父目录,以实现从给定ID获取完整的层级路径。示例数据展示了一个包含ID、标题、控制器、方法和父ID的表格结构,用于解释查询需求。查询的目标是从特定ID出发,得到包括自身在内的所有上级记录。
摘要由CSDN通过智能技术生成

我有这个架构

样本数据

| ID | TITLE | CONTROLLER | METHOD | PARENT_ID |

|----|-------------------|------------|-------------------|-----------|

| 1 | Dashboard | admin | dashboard | 0 |

| 2 | Content | admin | content | 0 |

| 3 | Modules | admin | modules | 0 |

| 4 | Users | admin | users | 0 |

| 5 | Settings | admin | settings | 0 |

| 6 | Reports | admin | reports | 0 |

| 7 | Help | admin | help | 0 |

| 8 | Pages | content | pages | 2 |

| 9 | Media | content | media | 2 |

| 10 | Articles | content | articles | 2 |

| 11 | Menues | content | menues | 2 |

| 12 | Templates | content | templates | 2 |

| 13 | Themes | content | themes | 2 |

| 14 | Blog | content | blog | 2 |

| 15 | Forum | content | forum | 2 |

| 16 | Core Modules | modules | core_module | 3 |

| 17 | User Modules | modules | user_module | 3 |

| 18 | All Users | users | all_users | 4 |

| 19 | Groups | users | groups | 4 |

| 20 | Permissions | users | permissions | 4 |

| 21 | Import and Export | users | import_export | 4 |

| 22 | Send Email | users | send_mail | 4 |

| 23 | Login Records | users | login_records | 4 |

| 24 | General Settings | settings | general_settings | 5 |

| 25 | Email Settings | settings | email_settings | 5 |

| 26 | Popular Content | reports | popular_content | 6 |

| 27 | Most Active Users | reports | most_active_users | 6 |

| 28 | Documentation | help | documentation | 7 |

| 29 | About | help | about | 7 |

| 30 | Products | products | product | 17 |

| 31 | Categories | categories | category | 17 |

SQL Fiddle演示。我已经插入了一些示例数据。

查兰芝

我需要找到唱片标题的所有父母Categories。如何仅通过一个查询就可以获取所有父母?

我的意思是我需要这个结果:

期望的输出

id | title | controller | method | url | parent_id

----------------------------------------------------------------

3 | Modules | admin | modules | (NULL) | 0

17 | User Modules | modules | user_module | (NULL) | 3

31 | Categories | categories | category | (NULL) | 17

假设我想使用其所有父项来获取条目,并且要使用where条件id = 31,那么它应该获取上述记录。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值