php - 使用mysql递归统计经理下的员工

标签 php mysql

我需要使用下表中的 MYSQL,按照经理的层次结构获得所有员工的列表。在oracle或mssql中这很容易,但在MySQL中找不到任何解决方案。谁能帮我解决一下。

id  name    manager

1   John    6
2   Gill    7
3   Ben     2
4   Roy     8
5   Lenin   6
6   Nancy   7
7   Sam     0
8   Dolly   3

最佳答案

如果您仍然可以限制最大级别数,这里有一个递归过程的解决方案。由于 MySQL 中不允许使用递归函数,因此我们这里有一个函数 (manager_count),它包装了递归过程的结果。递归深度由 max_sp_recursion_depth 变量控制,其中takes 255 as its maximum 。使用如下:SELECT *,manager_count(id) FROM my_table。这不是最佳解决方案,因为它没有考虑层次结构中已计数的分支(临时表实际上可以用作缓存)。

DELIMITER //
DROP FUNCTION IF EXISTS manager_count//
CREATE FUNCTION manager_count(_manager INT) RETURNS INT
BEGIN
    DECLARE _count INT DEFAULT 0;
    SET max_sp_recursion_depth = 255;
    # manager_count_helper does the job
    CALL manager_count_helper(_manager, _count);
    # subtract 1, because manager_count_helper will count this manager as well
    RETURN _count - 1;
END//

DROP PROCEDURE IF EXISTS manager_count_helper//
CREATE PROCEDURE manager_count_helper(IN _manager INT, INOUT _count INT)
BEGIN
    IF EXISTS (SELECT 1 FROM my_table WHERE id = _manager) THEN
    BEGIN
        DECLARE _next_manager INT DEFAULT 0;
        DECLARE done BOOLEAN DEFAULT FALSE;
        # cursor to loop through the employees
        DECLARE _cursor CURSOR FOR SELECT id FROM my_table WHERE manager = _manager;
        # if done, the done variable gets TRUE and it's time too leave
        DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
        # count 1, because this guy should be counted as well
        SET _count = _count + 1;
        OPEN  _cursor;
        read_loop: LOOP
            FETCH  _cursor INTO _next_manager;
            IF done THEN LEAVE read_loop;
            END IF;
            CALL manager_count_helper(_next_manager, _count);
        END LOOP;
        CLOSE  _cursor;
    END;
    END IF;
END

关于php - 使用mysql递归统计经理下的员工,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20542312/

相关文章:

PHP 非法偏移类型

php - magento 以编程方式设置商店 ID

java - Php,克隆对象,添加新方法,或覆盖它们

mysql - c9.io 停止 apache 释放 process.env.PORT

php - 如何在 PHP 中显示 SUM 列

php - 在数据库中正确输入复选框值

php - 我想在Prestashop中通过id获取产品,并列出它们

php - 如何在不在查询中定义的情况下获取所有表列?

mysql - Flyway 脚本因单个 schema 中的两个 schema_version 表而失败[已解决]

python - 使用 Python 将新行追加到 MySQL 数据库中的现有字段