mysql表中的父树(while-loop)

时间:2013-08-13 08:43:10

标签: mysql sql loops select while-loop

抱歉我的英文。 我有一个像这样的mysql表

[ --------------------------]
[ parent_id ] [ category_id ]
[ --------------------------]

网站结构如下:

0
-> 1
-> 2
-> -> 3
-> -> -> 5
-> 4

和表格看起来像

0 1
0 2
2 3
0 4
3 5

如何编写mysql while循环到输入5并获取它的父级列表,直到0:

3
2

我知道,如何在php中编写它,但我只想对数据库进行1次查询,但是当我尝试从官方手册中运行“While”示例时,它会返回很多错误。

3 个答案:

答案 0 :(得分:0)

您可以通过程序实现此目的..

CREATE PROCEDURE `root_connect`(IN init char(1),OUT str char(15))
BEGIN
    set @startChar:=(select category_id from tableName where parent_id = init);
    set @endloop := "no";
    set @fullchar:= @startChar;
    set @newchar:= "";  
    if (@startChar !="-" OR @startChar =null) then 
        WHILE (@endloop = "no") DO                  
            set @newchar :=(select category_id from tableName where parent_id = @startChar);       
            if(@newchar = '-') THEN
                set @endloop := "yes";
            else
                set @fullchar:= concat(@fullchar,"-",@newchar);
            end if;         
            set @startChar := @newchar;     
        END WHILE;
    end if;
        select @fullchar;
END

答案 1 :(得分:0)

每个答案都不正确,但我已经完成了。 如果有人需要,试试这个。

DELIMITER $$
DROP PROCEDURE IF EXISTS `dbName`.`getParentsTree` $$
CREATE PROCEDURE `tableName`.`getParentsTree` (IN firstChild INT, OUT tree VARCHAR(255))
BEGIN
  set @newChar = (select `parent_id` from tableName where category_id = firstChild);
  set @fullchar = "";
  set @fullchar = @fullchar + firstChild;
  WHILE (@newChar != 0) DO
    SELECT CONCAT_WS(',', @fullChar, @newChar) INTO @fullChar;
    set @newChar = (select `parent_id` from tableName where category_id = @newChar);
  END WHILE;
  SELECT @fullchar INTO tree;
END $$
DELIMITER ;

CALL dbName.getParentsTree(46, @a);
SELECT @a;

答案 2 :(得分:0)

好的把你的答案放在一起我创造了这个:

DELIMITER $$
DROP PROCEDURE IF EXISTS `dbName`.`getParentsTree` $$
CREATE PROCEDURE `dbName`.`getParentsTree` (IN firstChild INT, OUT tree VARCHAR(255))
BEGIN
  set @newChar = (select `parent_id` from categories where id = firstChild);
  set @newName = (select `name` from categories where id = firstChild);
  set @fullchar = "" + @newName;
  WHILE (@newChar != 0) DO

    set @newChar = (select `parent_id` from categories where id = @newChar);
    set @newName = (select `name` from categories where id = @newChar);
    SELECT CONCAT_WS(' > ', @fullChar, @newName) INTO @fullChar;
  END WHILE;
  SELECT @fullchar INTO tree;
  END $$
  DELIMITER ;

访问程序

 CALL dbName.getParentsTree(460, @tree);
select @tree;