如何从我的 sql 数据正确构建深度为 n 的图
我有以下数据
| From | To |
+------+----+
| 1 | 2 |
| 2 | 3 |
| 2 | 4 |
| 5 | 1 |
| 6 | 5 |
| 5 | 7 |
+------+----+
现在我想使用 CTE 增强选择来查询我的数据,就像
DECLARE @start INT;
SET @start = 1;
DECLARE @depth INT;
SET @depth = 1;
WITH
[Recursive] AS
(
SELECT
1 as [level],
*
FROM [dbo].[myTable]
WHERE @start IN ([From], [To])
UNION ALL
SELECT
t1.[level] + 1,
t2.*
FROM [Recursive] t1
JOIN [dbo].[myTable] t2
ON t1.[level] < @depth
AND
(
t1.[From] IN (t2.[From], t2.[To])
OR t1.[To] IN (t2.[From], t2.[To])
)
)
SELECT DISTINCT
[From],
[To]
FROM [Recursive]
使用这个小测试数据一样,性能相当不错 - 但是当增加数据和深度时,执行变得非常糟糕(由多列联接引起) 。
对于这样的任务,正确的说法是什么?
I have following data
| From | To |
+------+----+
| 1 | 2 |
| 2 | 3 |
| 2 | 4 |
| 5 | 1 |
| 6 | 5 |
| 5 | 7 |
+------+----+
Now I would like to query my data with CTE enhanced select, like
DECLARE @start INT;
SET @start = 1;
DECLARE @depth INT;
SET @depth = 1;
WITH
[Recursive] AS
(
SELECT
1 as [level],
*
FROM [dbo].[myTable]
WHERE @start IN ([From], [To])
UNION ALL
SELECT
t1.[level] + 1,
t2.*
FROM [Recursive] t1
JOIN [dbo].[myTable] t2
ON t1.[level] < @depth
AND
(
t1.[From] IN (t2.[From], t2.[To])
OR t1.[To] IN (t2.[From], t2.[To])
)
)
SELECT DISTINCT
[From],
[To]
FROM [Recursive]
With this small test-data the performance is quite ok - but when increasing the data and depth the execution gets really bad (caused by multiple-column join).
What is the correct statement for such a task?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当我在客户端使用 C# 时,我最终将所有数据拉到客户端以及 C# 中的图形计算内容。它的性能更高,而且内存占用不是问题,我对此感到满意:)
As I use C# on my client-side, I ended up pulling all the data to the client and to the graph-calculation-stuff in C#. It's way more performant and as memory-footprint is not the problem, I am happy with that :)