我有以下架构,表示存储在MySQL中的图形。
Nodes
Id | Type
Links
Id | Source_id | Dest_id
其中source_id和dest_id是Nodes表的外键。 每个节点都可以有多个链接。
我想创建一个存储过程来从图中节点的给定id开始检索子图。 我正在查看此示例http://sqlfiddle.com/#!2/58c804/1,但仅当每个节点都有一个链接时才有效。我想我应该使用CURSOR,但我不知道如何让它发挥作用。
@C_B我尝试的是以下内容:
我有以下树:
5
|
1
/ \
2 3
/
4
CREATE TABLE Nodes
(`id` int, `type` varchar(10))
CREATE TABLE Links
(`id` int, `source_id` int, `dest_id` int)
INSERT INTO Nodes
(`id`, `type`)
VALUES
(1, 'a'),
(2, 'b'),
(3, 'c'),
(4, 'd'),
(5, 'e')
INSERT INTO Links
(`id`, `source_id`, `dest_id`)
VALUES
(1, 1, 2),
(2, 1, 3),
(3, 2, 4),
(4, 5, 1)
CREATE PROCEDURE get_subgraph(IN id int)
BEGIN
DECLARE prev_id int;
DECLARE child_id int;
DECLARE done INT DEFAULT FALSE;
SET prev_id = id;
DECLARE child_cursor CURSOR FOR
SELECT dest_id FROM Links WHERE source_id=prev_id ;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN child_cursor;
FETCH child_cursor INTO child_id;
CREATE TEMPORARY TABLE IF NOT EXISTS results AS (SELECT * FROM Links WHERE 1=0);
TRUNCATE TABLE results
WHILE child_id <> 0 DO
INSERT INTO results SELECT * FROM Links WHERE source_id=prev_id;
SET prev_id = child_id;
SET child_id=0;
FETCH child_cursor INTO child_id;
IF done THEN
SET done = FALSE;
CLOSE child_cursor;
DECLARE child_cursor CURSOR FOR
SELECT dest_id FROM results WHERE source_id=prev_id;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN child_cursor;
FETCH child_cursor INTO child_id;
END IF
END WHILE;
SELECT * FROM results;
END
我想打电话 CALL get_subgraph(1);
并得到以下结果:
结果
id | source_id | dest_id
1 | 1 | 2
2 | 1 | 3
3 | 2 | 4
非常感谢您的帮助