Home >Database >Mysql Tutorial >mysql家谱表查询某人所有后代

mysql家谱表查询某人所有后代

WBOY
WBOYOriginal
2016-06-07 14:56:191435browse

我们经常会把一些树形的结构放在一张表里,例如家谱,菜单等。这种表最大的问题就是当我们需要查询某个记录的所有子记录时,很难用简单的sql搞定。我们可以专门写个过程来做这种事情,下面是我写的一个例子。fghgfhgfhgf MySQL CREATE TABLE `people` ( `id`

我们经常会把一些树形的结构放在一张表里,例如家谱,菜单等。这种表最大的问题就是当我们需要查询某个记录的所有子记录时,很难用简单的sql搞定。我们可以专门写个过程来做这种事情,下面是我写的一个例子。fghgfhgfhgf MySQL
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
Statement:
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