我有一个数据库,其表格看起来像这样:
Root | Connector
A | B
B | C
C | D
D | E
E | -
所以我想检索任何给定root的链,直到连接器为空
例如:A链表示a-> B-> C-> D-> E,而C链表示C-> D-> E
我正在使用mysql数据库。
提前致谢
答案 0 :(得分:3)
我只是尝试在Mysql中使用循环结构并获得成功。发布仅分享 -
CREATE PROCEDURE `root_connect`(IN init char(1),OUT str char(15))
BEGIN
set @startChar:=(select connector from tableName where root = init);
set @endloop := "no";
set @fullchar:= @startChar;
set @newchar:= "";
if (@startChar !="-" OR @startChar =null) then
WHILE (@endloop = "no") DO
set @newchar :=(select connector from tableName where root = @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 :(得分:1)
由于MySQL不允许用户创建递归函数,让我向您展示使用存储过程:
假设您正在处理的表名为“test”。
DELIMITER $$
DROP PROCEDURE IF EXISTS build_chain$$
CREATE PROCEDURE build_chain(init CHAR(1))
BEGIN
IF init != '-' THEN
SET @r := (SELECT DISTINCT(root) FROM test WHERE root = init);
SET @search_type := TRUE;
SET @result := @r;
END IF;
SET @r := (SELECT DISTINCT(connector) FROM test WHERE root = @r AND connector != '-');
SET @result = CONCAT_WS('->', @result, @r);
SET @search_type = IF(@search_type, FALSE, TRUE);
IF @r IS NOT NULL THEN CALL build_chain('-'); ELSE SELECT @result AS result_chain; END IF;
END$$
DELIMITER ;
用法:
SET max_sp_recursion_depth = 255;
CALL build_chain('a');
结果(链)存储在@result变量中。
注意:您也可以使用MySQL以外的编程语言构建链。