mysql遞歸查詢組織機構

建立表,並添加測試數據

建立表

DROP TABLE IF EXISTS vrv_org_tab; 
CREATE TABLE vrv_org_tab ( 
id bigint(8) NOT NULL AUTO_INCREMENT, 
org_name varchar(50) NOT NULL, 
org_level int(4) NOT NULL DEFAULT ‘0’, 
org_parent_id bigint(8) NOT NULL DEFAULT ‘0’, 
PRIMARY KEY (id), 
UNIQUE KEY unique_org_name (org_name) 
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8;

添加數據

INSERT INTO vrv_org_tab VALUES (‘1’, ‘北信源’, ‘1’, ‘0’); 
INSERT INTO vrv_org_tab VALUES (‘2’, ‘北京’, ‘2’, ‘1’); 
INSERT INTO vrv_org_tab VALUES (‘3’, ‘南京’, ‘2’, ‘1’); 
INSERT INTO vrv_org_tab VALUES (‘4’, ‘武漢’, ‘2’, ‘1’); 
INSERT INTO vrv_org_tab VALUES (‘5’, ‘上海’, ‘2’, ‘1’); 
INSERT INTO vrv_org_tab VALUES (‘6’, ‘北京研發中心’, ‘3’, ‘2’); 
INSERT INTO vrv_org_tab VALUES (‘7’, ‘南京研發中心’, ‘3’, ‘3’); 
INSERT INTO vrv_org_tab VALUES (‘8’, ‘武漢研發中心’, ‘3’, ‘4’); 
INSERT INTO vrv_org_tab VALUES (‘9’, ‘上海研發中心’, ‘3’, ‘5’); 
INSERT INTO vrv_org_tab VALUES (‘10’, ‘北京EMM項目組’, ‘4’, ‘6’); 
INSERT INTO vrv_org_tab VALUES (‘11’, ‘北京linkdd項目組’, ‘4’, ‘6’); 
INSERT INTO vrv_org_tab VALUES (‘12’, ‘南京EMM項目組’, ‘4’, ‘7’); 
INSERT INTO vrv_org_tab VALUES (‘13’, ‘南京linkdd項目組’, ‘4’, ‘7’); 
INSERT INTO vrv_org_tab VALUES (‘14’, ‘武漢EMM項目組’, ‘4’, ‘8’); 
INSERT INTO vrv_org_tab VALUES (‘15’, ‘武漢linkdd項目組’, ‘4’, ‘8’); 
INSERT INTO vrv_org_tab VALUES (‘16’, ‘上海EMM項目組’, ‘4’, ‘9’); 
INSERT INTO vrv_org_tab VALUES (‘17’, ‘上海linkdd項目組’, ‘4’, ‘9’);

select * from vrv_org_tab; sql

這裏寫圖片描述

根據父id遞歸查詢全部子節點

建立函數函數

create function getChildrenOrg(orgid INT)
returns varchar(4000)
BEGIN
DECLARE oTemp VARCHAR(4000);
DECLARE oTempChild VARCHAR(4000);

SET oTemp = '';
SET oTempChild = CAST(orgid AS CHAR);

WHILE oTempChild IS NOT NULL
DO
SET oTemp = CONCAT(oTemp,',',oTempChild);
SELECT GROUP_CONCAT(id) INTO oTempChild FROM vrv_org_tab WHERE FIND_IN_SET(org_parent_id,oTempChild) > 0;
END WHILE;
RETURN oTemp;
END

根據函數查詢

這裏寫圖片描述

根據子id遞歸查詢全部父節點

根據子id查詢父節點就不那麼麻煩了,不須要寫遞歸函數,固然,你也能夠寫遞歸函數來查詢。我這邊提供的是不寫函數的方式。請看代碼測試

寫sql語句

SELECT id,org_name,org_level,org_parent_id
    FROM ( 
        SELECT 
                @r AS _id, 
                (SELECT @r := org_parent_id FROM vrv_org_tab WHERE id = _id) AS parent_id, 
                 @l := @l + 1 AS lvl 
        FROM 
                (SELECT @r := 10000, @l := 0) vars, 
                vrv_org_tab h 
        WHERE @r <> 0) T1 
    JOIN vrv_org_tab T2 
    ON T1._id = T2.id
ORDER BY id;

注意:你們看到那個10000了嗎,就是咱們的子節點id。 spa

這裏寫圖片描述

相關文章
相關標籤/搜索