How to write this recursion? And how to design the corresponding structure?

there is a database as follows:

< table > < thead > < tr > < th > id < / th > < th > pid < / th > < th > name < / th > < / tr > < / thead > < tbody > < tr > < td > 1 < / td > < td > 0 < / td > < td > a < / td > < / tr > < tr > < td > 2 < / td > < td > 1 < / td > < td > b < / td > < / tr > < tr > < td > 3 < / td > < td > 2 < / td > < td > c < / td > < / tr > < tr > < td > 4 < / td > < td > 2 < / td > < td > d < / td > < / tr > < tr > < td > 5 < / td > < td > 1 < / td > < td > e < / td > < / tr > < tr > < td > 6 < / td > < td > 2 < / td > < td > f < / td > < / tr > < tr > < td > 7 < / td > < td > 5 < / td > < td > g < / td > < / tr > < tr > < td > 8 < / td > < td > 5 < / td > < td > h < / td > < / tr > < tr > < td >. < / td > < td >. < / td > < td >. < / td > < / tr > < / tbody > < / table >

pid: represents parent ID

get this data and how to code the tree result (json format) back to the front end.

{
    "id": 1,
    "name": "a",
    "children": [
        {
            "id": 2,
            "name: "b",
            "children": [
                {
                    "id": 3,
                    "name": "c",
                    "children": [ ... ] // 
                },
                {...},
                {...},
            ]
        },
        {
            "id": 5,
            "name": "e",
            "children": [
                {
                    "id": 7,
                    "name": "g"
                },
                {
                    "id": 8,
                    "name": "h"
                }
            ]
        },
    ]
}

there is no limit to the number of sons down, and there is only one node at the top.

Aug.16,2021

CTE, supported by mysql since 8.0 is easy to implement recursion. If you are not this version, then basically can not be written by SQL, change the stored procedure.

stored procedure reference: https://blog.csdn.net/moyanxu.

CTE reference:

  https://www.yiibai.com/mysql/.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b37974-2c08e.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b37974-2c08e.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?