增强:mysql递归父子查询

时间:2014-02-12 17:04:47

标签: mysql sql recursion hierarchical-data

增强:mysql递归父子查询

所需输出:应具有父名称及其ID ,如下所示

SELECT id,GetAncestry(id) as parents from Table1 where id = 7;

ID       PARENTS
7        zubuntu  id=6 , ubuntu id=3, linux id=2, os id=1

所需的第二次查询:

SELECT id,GetAncestry(id) as parents from Table1 WHERE ID <= 7 ; 
'1', ''
'2', 'os id=1'
'3', 'linux id=2, os id=1'
'4', 'xbuntu id=3, linux id=2, os id=1'
'5', 'lbuntu id=3, linux id=2, os id=1'
'6', 'zbuntu id=3, linux id=2, os id=1'
'7', 'zubuntu 2  id=6 , ubuntu id=3, linux id=2, os id=1'

当前输出:

SELECT id,GetAncestry(id) as parents from Table1 where id = 7;

ID  PARENTS
7   6,3,2,1

第二次查询:

SELECT id,GetAncestry(id)作为父表从Table1 WHERE ID&lt; = 7;

'1', ''
'2', '  1'
'3', '  2 > 1'
'4', '  3 > 2 > 1'
'5', '  3 > 2 > 1'
'6', '  3 > 2 > 1'
'7', '  6 > 3 > 2 > 1'

下面是mysql转储和函数所需:     创建表Table1         (id int,name varchar(11),prent int);

INSERT INTO Table1
    (`id`, `name`, `prent`)
VALUES
    (1, 'os', NULL),
    (2, 'linux', '1'),
    (3, 'ubuntu', '2'),
    (4, 'xubuntu', '3'),
    (5, 'lubuntu', '3'),
    (6, 'zubuntu', '3'),
    (7, 'zubuntu 2', '6'),
    (8, 'suse', '2'),
    (9, 'fedora', '2'),
    (10, 'windowse', '1'),
    (11, 'windowse xp', '10'),
    (12, 'windowse 7', '10'),
    (13, 'windowse 8', '10'),
    (14, 'food', NULL),
    (15, 'dance', NULL) ; 

功能:

    CREATE FUNCTION `GetAncestry` (GivenID INT) RETURNS VARCHAR(1024)
DETERMINISTIC
BEGIN
    DECLARE rv VARCHAR(1024);
    DECLARE cm CHAR(1);
    DECLARE ch INT;

    SET rv = '';
    SET cm = '';
    SET ch = GivenID;
    WHILE ch > 0 DO
        SELECT IFNULL(`prent`,-1) INTO ch FROM
        (SELECT `prent` FROM Table1 WHERE id = ch) A;
        IF ch > 0 THEN
            SET rv = CONCAT(rv,cm,ch);
            SET cm = ',';
        END IF;
    END WHILE;
    RETURN rv;
END

0 个答案:

没有答案