在SQL Server中,我在表格中的From和To列中有(From,To)。
From To
- -
1 5
1 7
1 8
1 17
2 11
3 5
4 7
5 12
5 13
5 17
8 13
8 17
13 17
如何找到作为输入给出的任意两个n点之间的最长路径?例如,如果输入为1,17,则答案应为1 - 5 - 13 - 17
答案 0 :(得分:2)
<强> SQL DEMO 强>
WITH Path ( FromID, ToID, Length, nodes ) AS (
SELECT t1.FromID, t1.ToID, 0 as Length,
CAST( t1.FromID AS VARCHAR(max) ) +'-'+
CAST( t1.ToID AS VARCHAR(max) ) as nodes
FROM Table1 t1
UNION ALL
SELECT P.FromID, t2.ToID, P.Length + 1,
P.nodes + '-' + CAST(t2.ToID AS VARCHAR(max) ) as nodes
FROM Table1 t2
JOIN Path P
ON P.ToID = t2.FromID
)
SELECT *
FROM Path
WHERE FromID = 1
and ToID = 17
Order by Length
<强>输出强>
从1到17,有两条长度为2的路径
| FromID | ToID | Length | nodes |
|--------|------|--------|-----------|
| 1 | 17 | 0 | 1-17 |
| 1 | 17 | 1 | 1-8-17 |
| 1 | 17 | 1 | 1-5-17 |
| 1 | 17 | 2 | 1-5-13-17 |
| 1 | 17 | 2 | 1-8-13-17 |