MySQL 中的一棵树中的子树
在我的 MYSQLDatabase COMPANY
中,我有一个Table: Employee
递归关联,一个员工可以是其他员工的老板。A self relationship of kind (SuperVisor (1)- SuperVisee (∞) )
.
查询创建表:
CREATE TABLE IF NOT EXISTS `Employee` (
`SSN` varchar(64) NOT NULL,
`Name` varchar(64) DEFAULT NULL,
`Designation` varchar(128) NOT NULL,
`MSSN` varchar(64) NOT NULL,
PRIMARY KEY (`SSN`),
CONSTRAINT `FK_Manager_Employee`
FOREIGN KEY (`MSSN`) REFERENCES Employee(SSN)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
我插入了一组元组(查询):
INSERT INTO Employee VALUES
("1", "A", "OWNER", "1"),
("2", "B", "BOSS", "1"), # Employees under OWNER
("3", "F", "BOSS", "1"),
("4", "C", "BOSS", "2"), # Employees under B
("5", "H", "BOSS", "2"),
("6", "L", "WORKER", "2"),
("7", "I", "BOSS", "2"),
# Remaining Leaf nodes
("8", "K", "WORKER", "3"), # Employee under F
("9", "J", "WORKER", "7"), # Employee under I
("10","G", "WORKER", "5"), # Employee under H
("11","D", "WORKER", "4"), # Employee under C
("12","E", "WORKER", "4")
插入的行具有以下Tree-Hierarchical-Relationship:
A <---ROOT-OWNER
/|\
/ A \
B F
//| \ \
// | \ K
/ | | \
I L H C
/ | / \
J G D E
我写了一个查询来查找关系:
SELECT SUPERVISOR.name AS SuperVisor,
GROUP_CONCAT(SUPERVISEE.name ORDER BY SUPERVISEE.name ) AS SuperVisee,
COUNT(*)
FROM Employee AS SUPERVISOR
INNER JOIN Employee SUPERVISEE ON SUPERVISOR.SSN = SUPERVISEE.MSSN
GROUP BY SuperVisor;
输出是:
+------------+------------+----------+
| SuperVisor | SuperVisee | COUNT(*) |
+------------+------------+----------+
| A | A,B,F | 3 |
| B | C,H,I,L | 4 |
| C | D,E | 2 |
| F | K | 1 |
| H | G | 1 |
| I | J | 1 |
+------------+------------+----------+
6 rows in set (0.00 sec)
[问题]
而不是完整的层次树,我需要一个SUB-TREE
点(选择性)例如:
如果输入参数是B
那么输出应该如下......
+------------+------------+----------+
| SuperVisor | SuperVisee | COUNT(*) |
+------------+------------+----------+
| B | C,H,I,L | 4 |
| C | D,E | 2 |
| H | G | 1 |
| I | J | 1 |
+------------+------------+----------+
请帮助我。如果不查询,存储过程可能会有所帮助。
我试过了,但所有的努力都是徒劳的!
我已经使用存储过程解决了这种性质的问题:查找分层字段的最高级别:有与没有 CTE(2011 年 10 月 24 日)
如果您查看我的帖子,您可以使用 GetAncestry 和 GetFamilyTree 函数作为从任何给定点遍历树的模型。
更新 2012-12-11 12:11 EDT
我从帖子中回顾了我的代码。我为你写了存储函数:
它确实有效。这是一个示例:
只有一个捕获。我为所有者添加了额外的一行
这是数据
您使用的称为Adjacency List Model。它有很多限制。当您想在特定位置删除/插入节点时,您会遇到问题。最好使用嵌套集模型。
有详细的解释。不幸的是,mysql.com 上的文章不再存在。