使用单个查询(递归查询)在 mysql 表中查找所有父项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12948009/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finding all parents in mysql table with single query (Recursive Query)
提问by Muhammad Raheel
I have this schema
我有这个架构
Sample Data
样本数据
| 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 demo.I have inserted some sample data.
SQL 小提琴演示。我插入了一些示例数据。
Challange
挑战
I need to find all the parents of the record where the title is Categories
. How can I get all the parents with only a single query?
I mean I need this result:
我需要找到标题所在的记录的所有父级Categories
。我怎样才能只用一个查询就得到所有的父母?
我的意思是我需要这个结果:
Desired Output
期望输出
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
Let suppose I want to fetch an entry with all of its parent and I want to use the where condition id = 31
, it should fetch above records.
假设我想获取一个条目及其所有父项,并且我想使用 where 条件id = 31
,它应该获取以上记录。