首页 > 解决方案 > Mysql - 如何仅使用祖先 id 获取所有后代(甚至孙子等..)?

问题描述

我确实想从我的树中获取所有后代(包括孙子)ID,我将在其中输入父 ID。我目前使用闭包表作为我的方法。我有这个表用于存储父子 ID:

CREATE TABLE `treepaths` (
`ancestor` int(11) NOT NULL,
`descendant` int(11) NOT NULL,
 PRIMARY KEY (`ancestor`,`descendant`),
KEY `FK_Descendant_idx` (`descendant`),
CONSTRAINT `FK_Ancestor` FOREIGN KEY (`ancestor`) REFERENCES `organization` 
(`organization_id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `FK_Descendant` FOREIGN KEY (`descendant`) REFERENCES 
`organization` (`organization_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1

这是我插入数据的地方:

CREATE DEFINER=`root`@`localhost` PROCEDURE `CreateChild`(
Ancestor int,
Descendant int,

ParentID int,
ChildID int
)
BEGIN
INSERT INTO treepaths
VALUES (Ancestor, Descendant);
SELECT tree.ancestor, ChildID FROM treepaths tree
WHERE tree.descendant = ParentID
UNION ALL SELECT ChildID, ChildID; 
END

这是我读取数据的地方:

CREATE DEFINER=`root`@`localhost` PROCEDURE `GetOrganizationDescendant`(
Ancestor int
)
BEGIN
SELECT org.* FROM organization org 
JOIN treepaths tree ON org.organization_id = tree.descendant
WHERE tree.ancestor = Ancestor;
END

目前,它只检索父母的直系子女,而不是孙子女。有没有办法做到这一点?

更新 我使用邻接列表模型修改我的表作为参考。现在,我想将父级包含在表中。我该怎么做呢?这是上面参考的示例小提琴

标签: mysql

解决方案


我建议您切换到层次结构/树的嵌套集模型 - 让您尝试运行并且毫无疑问将来想要运行的各种查询的生活变得更加轻松


推荐阅读