MySQL-遞迴查詢方法解析

來源:互聯網
上載者:User

標籤:

MySQL-遞迴查詢方法解析,兄 弟 連教育幫大家做了個簡單的整理:有需要的朋友可以參考下哈。

 

 

首先

表結構和資料

 

CREATE TABLE `class` (  `classid` int(11) NOT NULL AUTO_INCREMENT,  `banji` int(11) DEFAULT NULL COMMENT ‘0‘,  `nianji` varchar(255) DEFAULT NULL,  PRIMARY KEY (`classid`)) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;-- ------------------------------ Records of class-- ----------------------------INSERT INTO `class` VALUES (‘1‘, ‘0‘, ‘1‘);INSERT INTO `class` VALUES (‘2‘, ‘1‘, ‘2‘);INSERT INTO `class` VALUES (‘3‘, ‘1‘, ‘f‘);INSERT INTO `class` VALUES (‘4‘, ‘2‘, ‘d‘);INSERT INTO `class` VALUES (‘5‘, ‘3‘, ‘s‘);INSERT INTO `class` VALUES (‘6‘, ‘0‘, ‘a‘);INSERT INTO `class` VALUES (‘7‘, ‘6‘, ‘q‘);INSERT INTO `class` VALUES (‘8‘, ‘7‘, ‘h‘);INSERT INTO `class` VALUES (‘9‘, ‘5‘, ‘額‘);INSERT INTO `class` VALUES (‘10‘, ‘4‘, ‘121‘);

 

方法解析1

一級寫一個查詢結果聯合起來

 

SELECT * from class WHERE classid =1UNIONSELECT * FROM class where banji in(SELECT classid from class  WHERE classid =1 )UNION SELECT * FROM class where banji in (SELECT classid FROM class where banji in(SELECT classid from class  WHERE classid =1))

 

方法解析2

使用函數方法

建立函數來擷取個節點的值

 

CREATE FUNCTION `selectTree`(`id` int) RETURNS varchar(2000)BEGIN #Routine body goes here... DECLARE st VARCHAR(4000); DECLARE stcc VARCHAR(2000);#給st賦初值不能null,null會沒有傳回值 set st=‘‘; set stcc=id;#判斷stcc的是否為null WHILE stcc is not NULL DO#拼接字串賦值給st SET st=CONCAT(st,‘,‘,stcc); SELECT GROUP_CONCAT(classid) INTO stcc FROM class where FIND_IN_SET(banji,stcc)>0;END WHILE; RETURN st;END;

 

調用函數查出結果

SELECT * from  class where classid in (SELECT a.ban FROM class a,class b where a.banji=b.classid)  and banji=0

MySQL-遞迴查詢方法解析

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.