SQL 查询以通过根 ID 获取整棵树

SQL query to obtain entire tree by root id

我有一个table存储二叉树数据的结构如下

假设 userId 27,目前我正在获取一堆行并在代码中构建树。
有没有一种有效的方法可以通过 sql 查询获取属于 userId 27(作为节点)的树的所有行?
我有 MySQL 8.0.21.

在MySQL8.0中,一个选项使用递归查询:

with recursive cte as (
    select t.* from mytable where userid = 27
    union all
    select t.*
    from cte c
    inner join mytable t on t.parentid = c.userid
)
select * from cte