INSERT INTO `treepaths` VALUES (1, 1); INSERT INTO `treepaths` VALUES (1, 2); INSERT INTO `treepaths` VALUES (1, 3); INSERT INTO `treepaths` VALUES (1, 4); INSERT INTO `treepaths` VALUES (1, 5); INSERT INTO `treepaths` VALUES (1, 6); INSERT INTO `treepaths` VALUES (1, 7); INSERT INTO `treepaths` VALUES (2, 2); INSERT INTO `treepaths` VALUES (2, 3); INSERT INTO `treepaths` VALUES (3, 3); INSERT INTO `treepaths` VALUES (4, 4); INSERT INTO `treepaths` VALUES (4, 5); INSERT INTO `treepaths` VALUES (4, 6); INSERT INTO `treepaths` VALUES (4, 7); INSERT INTO `treepaths` VALUES (5, 5); INSERT INTO `treepaths` VALUES (6, 6); INSERT INTO `treepaths` VALUES (6, 7); INSERT INTO `treepaths` VALUES (7, 7);
每一条记录代表父节点和子节点之间有一条边,包括自己指向自己的边。
获取评论#4的子节点,只需要获取所有父节点是4的节点。
1 2 3 4 5 6 7 8
SELECT c.*, t.* FROM comments AS c JOIN TreePaths AS t ON c.comment_id = t.descendant WHERE t.ancestor =4;
获取评论#4的父节点,类似地查询节点子节点是#4的。
1 2 3 4 5 6 7 8
SELECT c.*, t.* FROM comments AS c JOIN TreePaths AS t ON c.comment_id = t.ancestor WHERE t.descendant =4;
插入节点时,插入节点 = 新增节点父节点的所有父节点 + 指向自身节点
向节点1插入节点2时,查找节点1的所有父节点(包括自身),然后UNION新增节点指向自身的记录
1 2 3 4 5 6 7 8 9 10 11 12
INSERT INTO `comment`(id) values(2); # 1,1 INSERT INTO TreePaths ( ancestor, descendant) SELECT t.ancestor, 1 FROM rel AS t WHERE t.descendant =1UNIONALL SELECT 2, 2;
删除一棵子树,应删除所有后代为该节点的记录,和以该节点作为后代的记录。
1 2 3 4 5
DELETE FROM TreePaths WHERE descendant IN ( SELECT descendant FROM ( SELECT descendant FROM TreePaths WHERE ancestor =4 ) AS b );