MySQL:树层次查询


20

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 |
+------------+------------+----------+   

请帮我。如果不查询,则存储过程可能会有所帮助。
我尝试了,但是所有的努力都没有用!



我只是为社区提供了一个测试框架,以便更轻松地探讨这个问题。
mellamokb

@bluefeet是的,一旦我得到答复,我将删除这两个之一。
Grijesh Chauhan

1
@GrijeshChauhan让我问你一个问题:哪种方法可以使自己可见的波浪?将卵石扔进大海,还是将石头扔进一个小池塘?几乎可以肯定的是,直接咨询专家们将为您提供最佳答案,而此类问题是如此重要(高级数据库主题),以至于我们已在网络上为其提供了自己的站点。但我不会阻止您询问您喜欢的地方,那是您的特权。我的特权是投票表决将它移到另一个站点(如果我认为它属于该站点)。:D在这种情况下,我们都使用我们认为合适的网络:D
jcolebrand

1
@jcolebrand:其实这只是我的错。我经常在多个方面发布问题,以获得更好,更快和更多的答复。It my experience 我总是从专家那边得到更好的答案。而且我认为将问题移交给数据库管理员是更好的决定。在所有情况下,我都非常感谢stackoverflow和在这里活跃的人们。对于很多很难找到自己或任何其他网站的问题,我确实有解决方案。
Grijesh Chauhan

Answers:


5

我已经使用存储过程解决了这种性质的问题:查找层次结构字段的最高级别:带或不带CTE(2011年10月24日)

如果查看我的文章,可以将GetAncestry和GetFamilyTree函数用作从任何给定点遍历树的模型。

更新2012-12-11 12:11 EDT

我回头看了看我的代码。我为您编写了存储功能:

DELIMITER $$

DROP FUNCTION IF EXISTS `cte_test`.`GetFamilyTree` $$
CREATE FUNCTION `cte_test`.`GetFamilyTree`(GivenName varchar(64))
RETURNS varchar(1024) CHARSET latin1
DETERMINISTIC
BEGIN

    DECLARE rv,q,queue,queue_children,queue_names VARCHAR(1024);
    DECLARE queue_length,pos INT;
    DECLARE GivenSSN,front_ssn VARCHAR(64);

    SET rv = '';

    SELECT SSN INTO GivenSSN
    FROM Employee
    WHERE name = GivenName
    AND Designation <> 'OWNER';
    IF ISNULL(GivenSSN) THEN
        RETURN ev;
    END IF;

    SET queue = GivenSSN;
    SET queue_length = 1;

    WHILE queue_length > 0 DO
        IF queue_length = 1 THEN
            SET front_ssn = queue;
            SET queue = '';
        ELSE
            SET pos = LOCATE(',',queue);
            SET front_ssn = LEFT(queue,pos - 1);
            SET q = SUBSTR(queue,pos + 1);
            SET queue = q;
        END IF;
        SET queue_length = queue_length - 1;
        SELECT IFNULL(qc,'') INTO queue_children
        FROM
        (
            SELECT GROUP_CONCAT(SSN) qc FROM Employee
            WHERE MSSN = front_ssn AND Designation <> 'OWNER'
        ) A;
        SELECT IFNULL(qc,'') INTO queue_names
        FROM
        (
            SELECT GROUP_CONCAT(name) qc FROM Employee
            WHERE MSSN = front_ssn AND Designation <> 'OWNER'
        ) A;
        IF LENGTH(queue_children) = 0 THEN
            IF LENGTH(queue) = 0 THEN
                SET queue_length = 0;
            END IF;
        ELSE
            IF LENGTH(rv) = 0 THEN
                SET rv = queue_names;
            ELSE
                SET rv = CONCAT(rv,',',queue_names);
            END IF;
            IF LENGTH(queue) = 0 THEN
                SET queue = queue_children;
            ELSE
                SET queue = CONCAT(queue,',',queue_children);
            END IF;
            SET queue_length = LENGTH(queue) - LENGTH(REPLACE(queue,',','')) + 1;
        END IF;
    END WHILE;

    RETURN rv;

END $$

它确实有效。这是一个示例:

mysql> SELECT name,GetFamilyTree(name) FamilyTree
    -> FROM Employee WHERE Designation <> 'OWNER';
+------+-----------------------+
| name | FamilyTree            |
+------+-----------------------+
| A    | B,F,C,H,L,I,K,D,E,G,J |
| G    |                       |
| D    |                       |
| E    |                       |
| B    | C,H,L,I,D,E,G,J       |
| F    | K                     |
| C    | D,E                   |
| H    | G                     |
| L    |                       |
| I    | J                     |
| K    |                       |
| J    |                       |
+------+-----------------------+
12 rows in set (0.36 sec)

mysql>

只有一个收获。我为所有者增加了一行

  • 所有者的SSN为0
  • 所有者是他自己的老板,拥有MSSN 0

这是数据

mysql> select * from Employee;
+-----+------+-------------+------+
| SSN | Name | Designation | MSSN |
+-----+------+-------------+------+
| 0   | A    | OWNER       | 0    |
| 1   | A    | BOSS        | 0    |
| 10  | G    | WORKER      | 5    |
| 11  | D    | WORKER      | 4    |
| 12  | E    | WORKER      | 4    |
| 2   | B    | BOSS        | 1    |
| 3   | F    | BOSS        | 1    |
| 4   | C    | BOSS        | 2    |
| 5   | H    | BOSS        | 2    |
| 6   | L    | WORKER      | 2    |
| 7   | I    | BOSS        | 2    |
| 8   | K    | WORKER      | 3    |
| 9   | J    | WORKER      | 7    |
+-----+------+-------------+------+
13 rows in set (0.00 sec)

mysql>

了解这个主意!
Grijesh Chauhan

我如何能适应得到的所有后代A这样 A A/B A/B/C A/B/C/D A/B/C/E A/B/H A/B/H/G A/B/I A/B/I/J A/B/L A/F A/F/K
史密斯

它也可以处理多节点吗?因为它是挂在我的数据库而父母的多个节点发现
عثمانغني

3

您所使用的称为邻接列表模型。它有很多限制。要在特定位置删除/插入节点时会遇到问题。最好使用嵌套集模型

详细的解释。不幸的是,关于mysql.com的文章已不复存在。


5
它有很多限制 ”-但仅在使用MySQL时。几乎所有的DBMS都支持递归查询(MySQL是很少的递归查询之一),这使得该模型真正易于处理。
a_horse_with_no_name 2012年

@a_horse_with_no_name除了MySQL外,从没有使用过其他任何东西。所以我从来不知道。感谢您的信息。
Shiplu Mokaddim
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.