mysql 如何获取其及其所有子孙的数据或id (一)

mysql 如何获取其及其所有子孙的数据或id (一)

/* 通过组织机构i数据获取其所有子孙数据*/
WITH RECURSIVE cte AS
(SELECT * FROM organization WHERE organization_id = 1
UNION ALL
SELECT organization.* FROM organization INNER JOIN cte ON organization.parent_id = cte.organization_id)
SELECT * FROM cte;

效果如下:
mysql 如何获取其及其所有子孙的数据或id (一)

/* 通过组织机构id获取其所有子孙id*/
WITH RECURSIVE cte AS
(SELECT organization_id FROM organization WHERE organization_id = 1
UNION ALL
SELECT organization.organization_id FROM organization INNER JOIN cte ON organization.parent_id = cte.organization_id)
SELECT * FROM cte;

效果如下:
mysql 如何获取其及其所有子孙的数据或id (一)

WITH RECURSIVE cte 该语法只能在mysql 8.0才能使用,那之前的版本怎么做的呢?存储函数,点击下面的链接查看。
mysql 如何获取其及其所有子孙的数据或id (二)

想看更多精彩内容,可以关注我的博客园
我的博客园

上一篇:ACM 对决


下一篇:Mysql:简单存储过程