mysql内部所有父子的连接

时间:2014-02-28 21:31:23

标签: mysql database-design relational-database

我有一个结构为

的表格
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个房间。

父字段保持为null(如果没有父项 - 节点 - )或父项的Id。

我想获取父行的所有行

我希望我的查询能够归还所有孩子和孩子的孩子。

我可以使用一个查询执行此操作吗?

1 个答案:

答案 0 :(得分:1)

除非你有一个固定的层次结构深度,否则我想不出你如何在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
    致电stackoverflowparent_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
* http://dev.mysql.com/doc/refman/5.6/en/server-system-variables.html#sysvar_max_sp_recursion_depth
* MySql :: stored procedure recursive
* http://www.tutorialspoint.com/mysql/mysql-temporary-tables.htm
* How to get depth in mysql store procedure recursion?