mysql - 循环查找父ID,直到它给出null
问题描述
谁能帮我查询。我和下面的图片1有同样的问题。不同的是,我在图 2 中的数据与他的不同。如果我搜索用户 id,它会给我父 id,然后它会在用户 id 中搜索父 id,直到它给出 null。谢谢你。
解决方案
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 ;
推荐阅读
- php - PHPMailer - 文件附件错误
- visual-studio-2017 - 无法运行 2020 年 12 月的 Visual Studio 2017 Enterprise 更新
- xcode - Xcode中是否有最大数量的子项目
- discord - 如何删除 discord.js v12 中的消息
- php - 您能否在一个查询中从同一个表中提取所有父子关系列,同时保持正确的顺序?
- python - 将单个图加载到 pytorch 几何数据对象中以进行节点分类
- jenkins - Jenkinsfile 管道选项:等效时
- asp.net - 在 Visual Studio 中从 IIS 打开网站会重新启动网站
- android - Android Kotlin:如何在片段中垂直对齐 RecyclerView
- sublimetext3 - XML 语法高亮中的嵌入式 JS