如何创建 MySQL 分层递归查询? - How to create a MySQL hierarchical recursive query?

语言: CN / TW / HK

问题:

I have a MySQL table which is as follows:我有一个 MySQL 表,如下所示:

id ID name名称 parent_id parent_id
19 19 category1类别1 0 0
20 20 category2类别2 19 19
21 21 category3类别3 20 20
22 22 category4类别4 21 21
... ... ... ... ... ...

Now, I want to have a single MySQL query to which I simply supply the id [for instance say id=19 ] then I should get all its child ids [ie result should have ids '20,21,22']....现在,我想要一个 MySQL 查询,我只需提供 id [例如说id=19 ] 然后我应该得到它的所有子 ID [即结果应该有 ids '20,21,22'] ... .

The hierarchy of the children is not known;孩子的等级是未知的; it can vary....它可以变化....

I know how to do it using a for loop... but how to achieve the same using a single MySQL query?我知道如何使用for循环来实现……但是如何使用单个 MySQL 查询来实现相同的目标?


解决方案:

参考一: https://stackoom.com/question/1Mp2O
参考二: How to create a MySQL hierarchical recursive query?
「其他文章」