Parents tree in mysql table (while-loop)

2019-09-21 15:08发布

Sorry for my English. I have a mysql table like this

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

Site structured like this:

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

and table will look like

0 1
0 2
2 3
0 4
3 5

How to write mysql while loop to input 5 and get list of it's parents until 0:

3
2

I know, how to write it in php, but I want to do only 1 query to database, but when I try to run "While" examples from official manuals, it returns a lot of errors.

3条回答
爷的心禁止访问
2楼-- · 2019-09-21 15:34

You can achieve this with Procedures..

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
查看更多
爷、活的狠高调
3楼-- · 2019-09-21 15:48

Every answers are incorrect, but I've done it. If somebody will need, try this.

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;
查看更多
我命由我不由天
4楼-- · 2019-09-21 15:54

Ok putting your answers together I created this one:

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 ;

To access the procedure

 CALL dbName.getParentsTree(460, @tree);
select @tree;
查看更多
登录 后发表回答