在MySQL中若是是有限的層次,好比咱們事先若是能夠肯定這個樹的最大深度, 那麼全部節點爲根的樹的深度均不會超過樹的最大深度,則咱們能夠直接經過left join來實現。函數
但不少時候咱們是沒法控制或者是知道樹的深度的。這時就須要在MySQL中用存儲過程(函數)來實現或者在程序中使用遞歸來實現。本文討論在MySQL中使用函數來實現的方法:測試
1、環境準備spa
一、建表code
1 CREATE TABLE `table_name` ( 2 `id` int(11) NOT NULL AUTO_INCREMENT, 3 `status` int(255) NULL DEFAULT NULL, 4 `pid` int(11) NULL DEFAULT NULL, 5 PRIMARY KEY (`id`) USING BTREE 6 ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
二、插入數據blog
1 INSERT INTO `table_name` VALUES (1, 12, 0); 2 INSERT INTO `table_name` VALUES (2, 4, 1); 3 INSERT INTO `table_name` VALUES (3, 8, 2); 4 INSERT INTO `table_name` VALUES (4, 16, 3); 5 INSERT INTO `table_name` VALUES (5, 32, 3); 6 INSERT INTO `table_name` VALUES (6, 64, 3); 7 INSERT INTO `table_name` VALUES (7, 128, 6); 8 INSERT INTO `table_name` VALUES (8, 256, 7); 9 INSERT INTO `table_name` VALUES (9, 512, 8); 10 INSERT INTO `table_name` VALUES (10, 1024, 9); 11 INSERT INTO `table_name` VALUES (11, 2048, 10);
2、MySQL函數的編寫遞歸
一、查詢當前節點的全部父級節點ci
1 delimiter // 2 CREATE FUNCTION `getParentList`(root_id BIGINT) 3 RETURNS VARCHAR(1000) 4 BEGIN 5 DECLARE k INT DEFAULT 0; 6 DECLARE fid INT DEFAULT 1; 7 DECLARE str VARCHAR(1000) DEFAULT '$'; 8 WHILE rootId > 0 DO 9 SET fid=(SELECT pid FROM table_name WHERE root_id=id); 10 IF fid > 0 THEN 11 SET str = concat(str,',',fid); 12 SET root_id = fid; 13 ELSE 14 SET root_id=fid; 15 END IF; 16 END WHILE; 17 RETURN str; 18 END // 19 delimiter ;
二、查詢當前節點的全部子節點get
1 2 delimiter // 3 CREATE FUNCTION `getChildList`(root_id BIGINT) 4 RETURNS VARCHAR(1000) 5 BEGIN 6 DECLARE str VARCHAR(1000) ; 7 DECLARE cid VARCHAR(1000) ; 8 DECLARE k INT DEFAULT 0; 9 SET str = '$'; 10 SET cid = CAST(root_id AS CHAR);12 WHILE cid IS NOT NULL DO 13 IF k > 0 THEN 14 SET str = CONCAT(str,',',cid); 15 END IF; 16 SELECT GROUP_CONCAT(id) INTO cid FROM table_name WHERE FIND_IN_SET(pid,cid)>0; 17 SET k = k + 1; 18 END WHILE; 19 RETURN str; 20 END // 21 delimiter ;
3、測試it
一、獲取當前節點的全部父級table
SELECT getParentList(10);
二、獲取當前節點的全部字節
SELECT getChildList(3);
本文完......