mysql - 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
目前,它只检索父母的直系子女,而不是孙子女。有没有办法做到这一点?
解决方案
推荐阅读
- python - 如何从 XML int Python 中获得一些价值?
- python-2.7 - python 2.7 - 在 utf8 中编码操作系统
- javascript - Chart js:更新具有两个数据集的折线图
- asp.net-core - 如何在 Asp.net core1.1 中使多个设备的 jwt 令牌过期
- html - 我们如何改变块级元素的减小宽度的方向?
- c# - 建立SecurityContext="False" 和negotiateServiceCredential="False" 的安全含义是什么
- javascript - 数组中的随机项仅返回索引位置,而不是实际值
- linux - 在 RHEL 上安装 Docker 时出现错误
- c# - 如何在重新映射对象期间捕获空值/错误?
- swift - 'NSInvalidArgumentException',原因:'JSON 写入中的无效类型(_SwiftValue)'