如何获取mysql表的所有行父项

时间:2013-03-22 19:48:09

标签: mysql stored-procedures

我正在尝试创建一个存储过程,该存储过程返回给定id的父项的所有Id。这是我到目前为止所做的,并且出于所有意图和目的,该表由两列组成,id和ParentID。当前代码的结果是它似乎没有从表中获取ParentID,它只是尝试将传入的id两次添加到临时表,然后失败。我哪里出错了?

CREATE PROCEDURE `mydb`.`Test` (IN id int)
BEGIN
DECLARE parentId INT;
DECLARE n INT;

  DROP TEMPORARY TABLE IF EXISTS _1067_parents;

 CREATE TEMPORARY TABLE _1067_parents (
node_id INT NOT NULL PRIMARY KEY
  );
set n = 0;
set parentId := id;

get_parents_loop: LOOP
     set parentId := (select ParentID from mydb.myTable where TDOID = parentId);

    IF parentId is NULL THEN
      LEAVE get_parents_loop;
    END IF;

    INSERT INTO _1067_parents(node_id) Values (parentId);

END LOOP get_parents_loop;

 SELECT *
    FROM _1067_parents;

end

1 个答案:

答案 0 :(得分:1)

SQL Fiddle

MySQL 5.5.30架构设置

create table `MyTable`(`id` int primary key, `parentid` int)
//

insert `MyTable` (`id`, `parentid`) values
  (1, null), (2, 1), (3, 2)
//

CREATE PROCEDURE `Test` (IN cid int)
BEGIN
DECLARE parId INT;
DECLARE curId INT;

  DROP TEMPORARY TABLE IF EXISTS _1067_parents;

 CREATE TEMPORARY TABLE _1067_parents (
node_id INT NOT NULL PRIMARY KEY
  );

set curId := cid;
get_parents_loop: LOOP
    set parId := null;

    set parId = (select parentid from MyTable where id = curId);

    IF parId is NULL THEN
      LEAVE get_parents_loop;
    END IF;

    INSERT INTO _1067_parents(node_id) Values (parId);
    set curId := parId;

END LOOP get_parents_loop;


 SELECT *
    FROM _1067_parents;

end
//

show create procedure test;

查询1

call test(3)

<强> Results

| NODE_ID |
-----------
|       1 |
|       2 |