首页 > 解决方案 > 循环查找父ID,直到它给出null

问题描述

谁能帮我查询。我和下面的图片1有同样的问题。不同的是,我在图 2 中的数据与他的不同。如果我搜索用户 id,它会给我父 id,然后它会在用户 id 中搜索父 id,直到它给出 null。谢谢你。

图 1 图 2

在此处输入图像描述 在此处输入图像描述

标签: mysqlparent-child

解决方案


   with  cte(col1,col2,col3) as (
      select     col1,
                 col2,
                 col3
      from       sample1 
      where      col1 = 1
      union all
      select     yt.col1,
                 yt.col2,
                 yt.col3
      from       sample1 yt
      inner join cte 
      On yt.col1 = cte.col3
    )
    select * from cte

您将看到 col1=1 的结果

在此处输入图像描述

我添加了此字段以显示存储过程示例。

DELIMITER //
CREATE PROCEDURE Recrusive(col VARCHAR(50))
BEGIN
 with  cte(col1,col2,col3) as (
      select     col1,
                 col2,
                 col3
      from       sample1 
      where      col1 = col
      union all
      select     yt.col1,
                 yt.col2,
                 yt.col3
      from       sample1 yt
      inner join cte 
      On yt.col1 = cte.col3
    )
    select * from cte

END//
DELIMITER ;

推荐阅读