我有一个表,它是点之间的路径列表。我想创建一个查询,以返回一个包含pointID和范围(点数)的列表。但是花了一天时间试图解决这个问题并且没有去任何地方,有没有人知道应该怎么做? (我是为MS-SQL 2005编写的)
-- fromPointID | toPointID |
---------------|-----------|
-- 1 | 2 |
-- 2 | 1 |
-- 1 | 3 |
-- 3 | 1 |
-- 2 | 3 |
-- 3 | 2 |
-- 4 | 2 |
-- 2 | 4 |
with PointRanges ([fromPointID], [toPointID], [Range])
AS
(
-- anchor member
SELECT [fromPointID],
[toPointID],
0 AS [Range]
FROM dbo.[Paths]
WHERE [toPointID] = 1
UNION ALL
-- recursive members
SELECT P.[fromPointID],
P.[toPointID],
[Range] + 1 AS [Range]
FROM dbo.[Paths] AS P
INNER JOIN PointRanges AS PR ON PR.[toPointID] = P.[fromPointID]
WHERE [Range] < 5 -- This part is just added to limit the size of the table being returned
--WHERE P.[fromPointID] NOT IN (SELECT [toPointID] FROM PointRanges)
--Cant do the where statment I want to because it wont allow recurssion in the sub query
)
SELECT * FROM PointRanges
--Want this returned
-- PointID | Range |
-----------|-------|
-- 1 | 0 |
-- 2 | 1 |
-- 3 | 1 |
-- 4 | 2 |
答案 0 :(得分:0)
Markus Jarderot的链接为此提供了一个很好的答案。我最终尝试使用他的答案,并尝试在C#和linq中重写我的问题,但它最终成为一个数学问题,而不是编码问题,因为我有一个数千点相互关联的表。这仍然是我感兴趣的东西,并试图通过阅读有关数学和图论的书籍来更好地理解,但如果有其他人遇到这个问题,我认为Markus Jarderot的链接是你会找到的最佳答案。