mysql 層級結構查詢

描述:最近遇到了一個問題,在mysql中如何完成節點下的全部節點或節點上的全部父節點的查詢? 在Oracle中咱們知道有一個Hierarchical Queries能夠經過CONNECT BY來查詢,可是,在MySQL中尚未對應的函數!!! 下面給出一個function來完成的方法 下面是sql腳本,想要運行的直接賦值粘貼進數據庫便可。node

好記性不如爛筆頭
下面給出一個function來完成的方法mysql

下面是sql腳本,想要運行的直接賦值粘貼進數據庫便可。sql

建立表treenodes(能夠根據須要進行更改)數據庫


– Table structure for treenodes 函數


DROP TABLE IF EXISTS treenodes;
CREATE TABLE treenodes (
id int(11) NOT NULL,
nodename varchar(20) DEFAULT NULL,
pid int(11) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;spa


– Table structure for treenodes 命令行


插入幾條數據code


– Records of treenodes blog


INSERT INTO treenodes VALUES (‘1’, ‘A’, ‘0’);
INSERT INTO treenodes VALUES (‘2’, ‘B’, ‘1’);
INSERT INTO treenodes VALUES (‘3’, ‘C’, ‘1’);
INSERT INTO treenodes VALUES (‘4’, ‘D’, ‘2’);
INSERT INTO treenodes VALUES (‘5’, ‘E’, ‘2’);
INSERT INTO treenodes VALUES (‘6’, ‘F’, ‘3’);
INSERT INTO treenodes VALUES (‘7’, ‘G’, ‘6’);
INSERT INTO treenodes VALUES (‘8’, ‘H’, ‘0’);
INSERT INTO treenodes VALUES (‘9’, ‘I’, ‘8’);
INSERT INTO treenodes VALUES (‘10’, ‘J’, ‘8’);
INSERT INTO treenodes VALUES (‘11’, ‘K’, ‘8’);
INSERT INTO treenodes VALUES (‘12’, ‘L’, ‘9’);
INSERT INTO treenodes VALUES (‘13’, ‘M’, ‘9’);
INSERT INTO treenodes VALUES (‘14’, ‘N’, ‘12’);
INSERT INTO treenodes VALUES (‘15’, ‘O’, ‘12’);
INSERT INTO treenodes VALUES (‘16’, ‘P’, ‘15’);
INSERT INTO treenodes VALUES (‘17’, ‘Q’, ‘15’); 

 


把下面的語句直接粘貼進命令行執行便可(注意修改傳入的參數,默認rootId,代表默認treenodes)遞歸

根據傳入id查詢全部父節點的id

delimiter // 
CREATE FUNCTION `getParList`(rootId INT)
RETURNS varchar(1000) 
BEGIN
    DECLARE sTemp VARCHAR(1000);
    DECLARE sTempPar VARCHAR(1000); 
    SET sTemp = ''; 
    SET sTempPar =rootId; 

    #循環遞歸
    WHILE sTempPar is not null DO 
        #判斷是不是第一個,不加的話第一個會爲空
        IF sTemp != '' THEN
            SET sTemp = concat(sTemp,',',sTempPar);
        ELSE
            SET sTemp = sTempPar;
        END IF;
        SET sTemp = concat(sTemp,',',sTempPar); 
        SELECT group_concat(pid) INTO sTempPar FROM treenodes where pid<>id and FIND_IN_SET(id,sTempPar)>0; 
    END WHILE; 

RETURN sTemp; 
END
//

 

 

執行命令

select * from treenodes where FIND_IN_SET(id,getParList(15));
結果:

 
根據傳入id查詢全部子節點的id

delimiter // 
CREATE FUNCTION `getChildList`(rootId INT)
RETURNS varchar(1000) 

BEGIN
    DECLARE sTemp VARCHAR(1000);
    DECLARE sTempChd VARCHAR(1000);

    SET sTemp = '$';
    SET sTempChd =cast(rootId as CHAR);

    WHILE sTempChd is not null DO
        SET sTemp = concat(sTemp,',',sTempChd);
        SELECT group_concat(id) INTO sTempChd FROM  treeNodes where FIND_IN_SET(pid,sTempChd)>0;
    END WHILE;
    RETURN sTemp; 
END
//

 

執行命令

select * from treenodes where FIND_IN_SET(id,getChildList(7));
結果:

相關文章
相關標籤/搜索