我有一张桌子的结构
Id int(10)
Parent int(10) --reference I'd
Name
此表包含组织结构。示例数据
Id | parent | name
1 Null organization A
2 1 Office A
3 1 Office B
4 3 Room 1
5 3 Room 2
`
这个例子简单地映射了那个组织。A有2间办公室,B办公室有2间房间。
父字段要么保持空(如果没有父-end节点-),要么保留父节点的Id。
我想获取父行的所有行。
我希望我的查询返回所有的孩子和孩子的孩子。
我可以用一个查询来完成这个任务吗?
发布于 2014-03-01 02:19:46
除非您有固定的层次结构深度,否则我想不出如何使用MySQL中的一个查询(可能总是出错)。如果层次结构深度小于255,则只需对以前创建的递归过程进行一次调用,如下所示。
内程序内
CREATE PROCEDURE `parent_child`(in `I_Parent` int)
BEGIN
DECLARE `V_done` INT;
DECLARE `V_Id` INT;
DECLARE `V_Parent` INT;
DECLARE `V_Name` VARCHAR(45);
DECLARE `cur1` CURSOR FOR SELECT * FROM `stackoverflow`.`parent_child` WHERE `Parent` = `I_Parent`;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET `V_done` = TRUE;
INSERT INTO `stackoverflow`.`parent_child_temp` SELECT `Id`, `Parent`, `Name` FROM `stackoverflow`.`parent_child` WHERE `Parent` IS NULL AND `Id` = `I_Parent`;
OPEN `cur1`;
read_loop: LOOP
FETCH `cur1` INTO `V_Id`, `V_Parent`, `V_Name` ;
IF `V_done` THEN
LEAVE read_loop;
END IF;
INSERT INTO `stackoverflow`.`parent_child_temp` SELECT `V_Id`, `V_Parent`, `V_Name`;
CALL `stackoverflow`.`parent_child`(V_Id);
END LOOP;
CLOSE `cur1`;
END
包装程序
CREATE PROCEDURE `parent_child_wrapper`(in `I_WrapperParent` int)
BEGIN
SET @@SESSION.max_sp_recursion_depth = 255;
DROP TABLE IF EXISTS `stackoverflow`.`parent_child_temp`;
CREATE TEMPORARY TABLE `stackoverflow`.`parent_child_temp` (id int, parent int, name varchar(45));
CALL `stackoverflow`.`parent_child`(`I_WrapperParent`);
SELECT * FROM `stackoverflow`.`parent_child_temp`;
END
调用SQL
CALL `stackoverflow`.`parent_child_wrapper`(1);
参考资料
*http://dev.mysql.com/doc/refman/5.0/en/cursors.html
*How I query (with mysql) column names that "unfortunately" have round brackets?
*http://www.sitepoint.com/cursors-mysql-stored-procedures/
*How to echo print statements while executing a sql script
*depth
*MySql :: stored procedure recursive
*http://www.tutorialspoint.com/mysql/mysql-temporary-tables.htm
https://stackoverflow.com/questions/22106233
复制相似问题