mysql 递归实例 父子节点层级递归

在Oracle中可以使用CONNECT  BY子句可以轻松的实现递归查询,在MSSQLServer和DB2中则可以使用WITH子句来实现递归查询,MYSQL中即不支持CONNECT  BY子句也不支持WITH子句,所以要实现递归查询就必须使用其他的方式来变通实现, 而且实现方案也随需求的不同而有差异。

下为mysql 使用程序过程的 递归实例(互联网整理),

1.创建表

按 Ctrl+C 复制代码
DROP TABLE IF EXISTS `item_category`; CREATE TABLE `item_category` ( `id` int(11) NOT NULL auto_increment, `catId` int(11) default NULL, `parentId` int(11) default NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=REDUNDANT;
按 Ctrl+C 复制代码

2,插入数据

INSERT INTO `item_category` VALUES (1,1,0);
INSERT INTO `item_category` VALUES (2,2,1);
INSERT INTO `item_category` VALUES (3,3,1);
INSERT INTO `item_category` VALUES (4,4,2);
INSERT INTO `item_category` VALUES (5,5,3);


3.创建存储过程

按 Ctrl+C 复制代码
DELIMITER // drop procedure if exists findLChild// CREATE PROCEDURE findLChild(iid bigint(20),layer bigint(20)) BEGIN create temporary table if not exists tmp_table (id bigint(20)); SET@@max_sp_recursion_depth=99; call iterative(iid,layer); select * from tmp_table; drop temporary table if exists tmp_table; END;// DELIMITER ; DELIMITER // drop procedure if exists iterative// CREATE PROCEDURE iterative(iid bigint(20),layer bigint(20)) BEGIN declare tid bigint(20) default -1; declare cur1 CURSOR FOR select catId from item_category where parentId=iid; declare CONTINUE HANDLER FOR SQLSTATE '02000' SET tid = null; if layer > 0 then OPEN cur1; FETCH cur1 INTO tid; WHILE(tid is not null) DO insert into tmp_table values(tid); call iterative(tid,layer-1); FETCH cur1 INTO tid; END WHILE; end if; END;// DELIMITER ;
按 Ctrl+C 复制代码


4.调用

call findLChild(1,50);


5 java 调用

复制代码
用JAVA执行存储过程并取得结果集的代码如下:
Connection con = new Connection();----假设这里已经取得一个有效连接.
ResultSet rs=null;
CallableStatement cstm = con.prepareCall("{CALL testrs(?)}");
cstm.setInt(1,2);----将存储过程的第一个参数填充值2.
boolean bl = cstm.execute();-----执行存储过程
while(bl){----若存储过程成功执行了,并且有结果集返回了,那么bl就是true
rs=cstm.getResultSet()----取得一个结果集,
while(rs.next()){
System.out.println(rs.getInt(1));--- 随便输出一个值。
}
bl=cstm.getMoreResultSet();----若还能取得结果集,则bl=true,这样就回到循环首部,继续取得结果集进行处理,若不再有结果集了,则bl=false。结果循环。
这样,只要三次循环,这个存储过程的三个结果集就可以被分别渠道并处理了。

你可能感兴趣的:(mysql 递归实例 父子节点层级递归)