mysql表中的父树(while循环)
对不起我的英语。 我有一个像这样的mysql表mysql表中的父树(while循环),mysql,sql,loops,select,while-loop,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
[ --------------------------]
[ 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编写,但我只想对数据库进行一次查询,但当我尝试运行官方手册中的“While”示例时,它会返回很多错误。您可以通过过程实现这一点
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
每个答案都是错误的,但我已经做到了。 如果有人需要,试试这个
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;
好的,把你的答案放在一起,我创建了这个:
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;
递归连接在mysql afaik中是不可能的,您必须在php中进行,或者更改表的结构,(为任何节点的最高父级添加一列,然后在php中构建树)可能重复的可能重复:嗨,什么是“46”的意思?@M.Pancadewa That's tree root id。