Home > Database > Mysql Tutorial > body text

Mysql genealogy table to query all descendants of a person

大家讲道理
Release: 2016-11-12 09:45:00
Original
2000 people have browsed it

CREATE TABLE `people` (
    `id` INT(11) NOT NULL,
    `name` VARCHAR(50) NULL DEFAULT NULL,
    `pid` INT(11) NOT NULL DEFAULT '0',
    PRIMARY KEY (`id`)
);
 
CREATE DEFINER=`root`@`%` PROCEDURE `getChildren`(IN `parentId` INT)
    LANGUAGE SQL
    NOT DETERMINISTIC
    CONTAINS SQL
    SQL SECURITY DEFINER
    COMMENT '获取某人所有后代'
BEGIN
    #存放结果的临时表
    DROP TABLE IF EXISTS children;
    CREATE TEMPORARY TABLE children SELECT 0 pLevel,p.* FROM `people` p WHERE id=parentId;
    #存放中间结果的临时表
    DROP TABLE IF EXISTS tem;
    CREATE TEMPORARY TABLE tem SELECT id FROM `people` limit 0;
     
    #逐级填充后代
    SET @pLevel=1;
    REPEAT
        #清空上次数据
        TRUNCATE TABLE tem;
        #将当前level的后代id放入临时表
        INSERT INTO tem SELECT p.id FROM `people` P, children c 
            WHERE p.pid=c.id AND    c.pLevel=(@pLevel-1);
        #将当前level的后代数据塞入结果临时表
        INSERT INTO children SELECT @pLevel pLevel,p.* FROM `people` p, tem t 
        WHERE p.id=t.id;
        SET @pLevel=@pLevel+1;
    UNTIL NOT EXISTS (SELECT * FROM tem) OR @pLevel > 10
    END REPEAT;
     
    #调整表结构,删除临时列和不需要的数据
    ALTER TABLE children DROP COLUMN pLevel;
    DELETE FROM children WHERE id=parentId;
     
    #返回结果
    SELECT * from children;
END
Copy after login

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template