在MySQL中获取分层数据

时间:2014-01-17 10:42:35

标签: mysql sql hierarchical-data

我想在查询中获取给定孩子下面所有孩子的详细信息 例如。  如果我给出等级4或(等级N)那么我想得到所有等级的所有细节(如L1到L4 / LN)

enter image description here

2 个答案:

答案 0 :(得分:2)

Found the answer from this Link

创建表:

DROP TABLE IF EXISTS pctable;
CREATE TABLE pctable
(
    id INT NOT NULL AUTO_INCREMENT,
    parent_id INT,
    PRIMARY KEY (id)
) ENGINE=MyISAM;

INSERT QUERY:

INSERT INTO pctable (parent_id) VALUES (0);
INSERT INTO pctable (parent_id) SELECT parent_id+1 FROM pctable;
INSERT INTO pctable (parent_id) SELECT parent_id+2 FROM pctable;
INSERT INTO pctable (parent_id) SELECT parent_id+3 FROM pctable;
INSERT INTO pctable (parent_id) SELECT parent_id+4 FROM pctable;
INSERT INTO pctable (parent_id) SELECT parent_id+5 FROM pctable;
SELECT * FROM pctable;

创建功能:

DELIMITER $$

DROP FUNCTION IF EXISTS `GetFamilyTree1` $$
CREATE FUNCTION `GetFamilyTree1` (GivenID INT) RETURNS varchar(1024) CHARSET latin1
DETERMINISTIC
BEGIN

    DECLARE rv,q,queue,queue_children VARCHAR(1024);
    DECLARE queue_length,front_id,pos INT;

    SET rv = '';
    SET queue = GivenID;
    SET queue_length = 1;

    WHILE queue_length > 0 DO
        SET front_id = FORMAT(queue,0);
        IF queue_length = 1 THEN
            SET queue = '';
        ELSE
            SET pos = LOCATE(',',queue) + 1;
            SET q = SUBSTR(queue,pos);
            SET queue = q;
        END IF;
        SET queue_length = queue_length - 1;

        SELECT IFNULL(qc,'') INTO queue_children
        FROM (SELECT GROUP_CONCAT(id) qc
        FROM pctable WHERE parent_id = front_id) 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_children;
            ELSE
                SET rv = CONCAT(rv,',',queue_children);
            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 $$
DELIMITER ;

NOW FIRE SELECT QUERY:

SELECT id,GetFamilyTree1(id) FROM pctable where id = 2;

****以上查询将给出id为2的孩子。****

2天后我得到解决方案..: - )

答案 1 :(得分:0)

我认为您的第n级查询可以使用SELF JOIN Like

来完成
SELECT a.name, b.name FROM clildparent a, clildparent b WHERE a.id = b.parent_id;

认为它会有所帮助!!