MySQL中的一个树内的子树
在我的MYSQL中Database 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 |
+------------+------------+----------+
请帮我。如果不查询,则存储过程可能会有所帮助。
我尝试了,但是所有的努力都没有用!
1
样本测试提琴
—
mellamokb
我只是为社区提供了一个测试框架,以便更轻松地探讨这个问题。
—
mellamokb
@bluefeet是的,一旦我得到答复,我将删除这两个之一。
—
Grijesh Chauhan
@GrijeshChauhan让我问你一个问题:哪种方法可以使自己可见的波浪?将卵石扔进大海,还是将石头扔进一个小池塘?几乎可以肯定的是,直接咨询专家们将为您提供最佳答案,而此类问题是如此重要(高级数据库主题),以至于我们已在网络上为其提供了自己的站点。但我不会阻止您询问您喜欢的地方,那是您的特权。我的特权是投票表决将它移到另一个站点(如果我认为它属于该站点)。:D在这种情况下,我们都使用我们认为合适的网络:D
—
jcolebrand
@jcolebrand:其实这只是我的错。我经常在多个方面发布问题,以获得更好,更快和更多的答复。
—
Grijesh Chauhan
It my experience
我总是从专家那边得到更好的答案。而且我认为将问题移交给数据库管理员是更好的决定。在所有情况下,我都非常感谢stackoverflow和在这里活跃的人们。对于很多很难找到自己或任何其他网站的问题,我确实有解决方案。