sql - 如何递归查找表中的所有匹配行?
问题描述
我试图在不诉诸技巧的情况下与现有数据库争吵。我需要在链接表中查询以递归查找所有匹配的 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。
解决方案
注意:此解决方案适用于 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;
推荐阅读
- python - 更改通过python发送电子邮件时显示的名称?
- jmeter - JMeter 作为 HTTP 服务器
- github - 将 Travis CI 的 github 问题评论为 TravisCIBot
- python - Python - 在一个函数中处理多个数据帧
- visual-studio-code - Visual Studio 代码关闭“另存为”/CTRL+SHIFT+S
- javascript - 如何在 React Bootstrap Modal 中获取点击的元素数据?
- reactjs - 如何在 ReactJS 中使条件递归函数返回(null)?
- java - 将对象上传到具有内容长度的 Google Firebase 云存储
- c++ - Fortran POINTER 由 ISO_C_BINDING 与 INTENT(IN) 传递给 C
- android - Android - How to slow down battery Drain