首页 > 解决方案 > 如何递归查找表中的所有匹配行?

问题描述

我试图在不诉诸技巧的情况下与现有数据库争吵。我需要在链接表中查询以递归查找所有匹配的 id。

我尝试了许多嵌套连接查询,但我不是 SQL 专家。我是一名程序员,当我使用简单的数据库时,像这样的复杂查询对我来说很困难。

我的表如下所示:

------------------------
| child_id | parent_ id|
________________________
    2           16
    3           16
    4           16 
    11          10
    12          11
    16          7
    17          10
    18          17
    19          7
    20          19
    21          10
    22          21
    23          22
    24          22
    26          20

我只知道顶级parent id。我想找到所有关联的子 ID。

如果parent ID是 7,我需要返回 16、19、2、3、4、20、26。

标签: sqlmariadb

解决方案


注意:此解决方案适用于 MariaDB 10.2.2 及更高版本。

尝试公用表表达式

with recursive cte(child_id, parent_id) as (
    select child_id, parent_id from MyTable
    where parent_id = 7    
       union all 
    select mt.child_id, mt.parent_id from MyTable mt
         inner join cte t on mt.parent_id = t.child_id
)
select * from cte;

推荐阅读