Questions about using SQL statement to realize infinite pole classification query

clipboard.png

as shown in the picture, when I get my son"s information, how can I find out his father"s grandfather"s information through his pid?

Feb.17,2022

if there are only these three levels, you can connect the table with yourself

. The

statement is:

select a.id as pid, a.name as pname, a.pid as ppid, b.name as ppname
from family a join family b on a.pid=b.id where a.id=pid;

instance:

db83-3306>>select * from family;
+----+--------+------+
| id | name   | pid  |
+----+--------+------+
|  1 |    |    0 |
|  2 |    |    1 |
|  3 |    |    2 |
|  4 |    |    2 |
+----+--------+------+

db83-3306>>select a.id as pid, a.name as pname, a.pid as ppid, b.name as ppname
    -> from family a join family b on a.pid=b.id where a.id=2;
+-----+--------+------+--------+
| pid | pname  | ppid | ppname |
+-----+--------+------+--------+
|   2 |    |    1 |    |
+-----+--------+------+--------+

if you don't know the series, you can query it with a statement similar to the following. @ r: = 2 is the query condition

SELECT T2.id, T2.name, T2.pid
FROM ( 
    SELECT 
        @r AS _id, 
        (SELECT @r := pid FROM family WHERE id = _id) AS pid, 
        @l := @l + 1 AS l
    FROM 
        (SELECT @r := 2, @l := 0) vars, 
        family h 
    WHERE @r != 0) T1 
JOIN family T2 
ON T1._id = T2.id 
ORDER BY T1.l;

effect

db83-3306>>SELECT T2.id, T2.name, T2.pid
    -> FROM ( 
    ->     SELECT 
    ->         @r AS _id, 
    ->         (SELECT @r := pid FROM family WHERE id = _id) AS pid, 
    ->         @l := @l + 1 AS l
    ->     FROM 
    ->         (SELECT @r := 2, @l := 0) vars, 
    ->         family h 
    ->     WHERE @r != 0) T1 
    -> JOIN family T2 
    -> ON T1._id = T2.id 
    -> ORDER BY T1.l;
+----+--------+------+
| id | name   | pid  |
+----+--------+------+
|  2 |    |    1 |
|  1 |    |    0 |
+----+--------+------+
2 rows in set (0.00 sec)
Menu