在PHP MySQL上选择嵌套记录

时间:2016-09-13 05:16:29

标签: php mysql laravel

我在数据库sql中有一个表,如下所示,我想根据id和多少记录(生成)显示它

+-------------------------------+
|      ID      |    Parent_ID   | 
+-------------------------------+
|      1       |        0       |
+-------------------------------+
|      2       |        1       |
+-------------------------------+
|      3       |        1       |
+-------------------------------+
|      4       |        2       |
+-------------------------------+
|      5       |        2       | 
+-------------------------------+
|      6       |        2       |
+-------------------------------+
|      7       |        2       |
+-------------------------------+
|      8       |        3       | 
+-------------------------------+
|      9       |        5       |
+-------------------------------+
|      10      |        7       |
+-------------------------------+
|      11       |       10      | 
+-------------------------------+
|      12       |       10      | 
.................................
The list goes on..

所以,如果我想选择ID = 2并记录从第1代到第4代,结果会是这样的

+-------------------------------+
|      ID      |    Parent_ID   | 
+-------------------------------+
|      2       |        1       |  -> 1st generation
+-------------------------------+
|      4       |        2       |  -> 2nd generation
+-------------------------------+
|      5       |        2       |  -> 2nd generation
+-------------------------------+
|      6       |        2       |  -> 2nd generation
+-------------------------------+
|      7       |        2       |  -> 2nd generation
+-------------------------------+
|      10      |        7       |  -> 3rd generation
+-------------------------------+
|      12       |       10      |  -> 4th generation
.................................

这一代并不总是从头开始,所以我从任何一代开始选择位置,任何想法如何在php或php laravel中使用MySQL数据库做到这一点?

0 个答案:

没有答案