-1

对不起我的英语不好。我有一个这样的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”示例时,它会返回很多错误。

4

3 回答 3

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
于 2013-08-13T08:49:41.577 回答
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;
于 2013-08-13T13:37:33.720 回答
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;
于 2014-04-23T07:28:35.977 回答