尝试:
CREATE TABLE test (
ID INTEGER NOT NULL,
SOURCE CHAR(2) NOT NULL,
DESTINATION CHAR(2) NOT NULL
);
INSERT INTO test VALUES (1, 'C1', 'C2');
INSERT INTO test VALUES (2, 'C3', 'C4');
INSERT INTO test VALUES (3, 'C3', 'C5');
INSERT INTO test VALUES (4, 'C4', 'C6');
INSERT INTO test VALUES (5, 'C8', 'C9');
INSERT INTO test VALUES (6, 'C2', 'C3');
然后:
SELECT
CONCAT_WS(
'->',
A.SOURCE,
A.DESTINATION,
B.DESTINATION,
C.DESTINATION,
D.DESTINATION
)
FROM test A
LEFT JOIN test B ON B.SOURCE = A.DESTINATION
LEFT JOIN test C ON C.SOURCE = B.DESTINATION
LEFT JOIN test D ON D.SOURCE = C.DESTINATION
WHERE
A.SOURCE = 'C1'
AND 'C6' IN (A.DESTINATION, B.DESTINATION, C.DESTINATION, D.DESTINATION);
这使:
C1->C2->C3->C4->C6
请记住,此示例仅给出最大深度为 4 的路径,但您可以轻松扩展它。此外,您将获得所有可能的路径(如果有多个)。所以你需要决定你选择哪一个。