sql 机构树找父节点
时间: 2023-09-09 19:12:58 浏览: 103
SQL 查询树形子节点.
5星 · 资源好评率100%
要在SQL中找到机构树的父节点,可以使用递归查询来实现。首先,需要知道要查询的机构的ID。然后,使用递归查询来逐级查找机构的父节点,直到找到根节点(即parentid为0的节点)。下面是一个示例的SQL查询语句:
```sql
WITH RECURSIVE tb (id, name, parentid) AS (
SELECT id, name, parentid FROM organization WHERE id = <要查询的机构ID>
UNION ALL
SELECT c.id, c.name, c.parentid FROM organization c JOIN tb t ON c.id = t.parentid
)
SELECT * FROM tb WHERE parentid = 0;
```
其中,`organization`是机构表的名称,`id`、`name`和`parentid`是表中的列名。
使用以上的SQL查询语句,可以找到指定机构的所有父节点,直到根节点。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* [SQL的递归查询子/父节点结构(MySQL)](https://blog.csdn.net/m0_46252893/article/details/129256248)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"]
- *3* [Java递归获取树父节点下的所有树子节点](https://blog.csdn.net/weixin_39903375/article/details/114134751)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文