如何从我的 sql 数据正确构建深度为 n 的图

发布于 2024-11-30 13:59:09 字数 856 浏览 0 评论 0原文

我有以下数据

| 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

暮倦 2024-12-07 13:59:09

当我在客户端使用 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 :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文