mysql8.0CTE實現遞迴查詢
+----+----------+--------------+
| ID | ParentID | name |
+----+----------+--------------+
| 1 | 0 | 河南省 |
| 2 | 1 | 信陽市 |
| 3 | 2 | 淮濱縣 |
| 4 | 3 | 蘆集鄉 |
| 5 | 1 | 安陽市 |
| 6 | 5 | 滑縣 |
| 7 | 6 | 老廟鄉 |
| 8 | 2 | 固始縣 |
| 9 | 8 | 李店鄉 |
| 10 | 2 | 息縣 |
| 11 | 10 | 關店鄉 |
| 12 | 3 | 鄧灣鄉 |
| 13 | 3 | 臺頭鄉 |
| 14 | 3 | 谷堆鄉 |
| 15 | 1 | 南陽市 |
| 16 | 15 | 方城縣 |
| 17 | 1 | 駐馬店市 |
| 18 | 17 | 正陽縣 |
+----+----------+--------------+
with recursive r as (
select * from test_area where id =11
union all select test_area.* from test_area,r where test_area.id=r.ParentID)
select * from r order by id;
+------+----------+-----------+
| ID | ParentID | name |
+------+----------+-----------+
| 1 | 0 | 河南省 |
| 2 | 1 | 信陽市 |
| 10 | 2 | 息縣 |
| 11 | 10 | 關店鄉 |
+------+----------+-----------+