gpt4 book ai didi

sql - 递归 CTE 如何与文档中的示例一起使用?

转载 作者:行者123 更新时间:2023-11-29 13:23:07 25 4
gpt4 key购买 nike

我今天正在研究 CTE 文档并尝试使用下面的示例(根据文档中的示例稍作修改):

WITH RECURSIVE t(n) AS (
VALUES (1), (2)
UNION ALL
(
SELECT n + 1
FROM t
WHERE n < 100
)
)
SELECT * FROM t;

这段代码输出

n
-----
1
2
2
3
3
4
4
5
5
6
6
7
7
8
8
9
9
10
10
11
11
12
12
13
13
...

这本身就很好。然而,在文档中,解释如下( https://www.postgresql.org/docs/9.1/static/queries-with.html ):

  1. Evaluate the non-recursive term. For UNION (but not UNION ALL), discard duplicate rows. Include all remaining rows in the result of the recursive query, and also place them in a temporary working table.
  2. So long as the working table is not empty, repeat these steps:

    1. Evaluate the recursive term, substituting the current contents of the working table for the recursive self-reference. For UNION (but not UNION ALL), discard duplicate rows and rows that duplicate any previous result row. Include all remaining rows in the result of the recursive query, and also place them in a temporary intermediate table.
    2. Replace the contents of the working table with the contents of the intermediate table, then empty the intermediate table.

我对解释的理解如下:

最初,我们将 (1), (2) 插入到工作表中。然后在递归步骤中,我们取工作表,当前有(1),(2)UNION ALL递归步骤的结果,返回(2), (3),然后将结果放入中间表

所以在第一次递归调用之后,我们在工作表中有(1), (2)(1), (2), (2 ), (3)中间表中。

然后我们用中间表的值替换工作表的值,然后清空中间表。所以现在 working table(1), (2), (2), (3)intermediate table 是空的。

现在下一个递归调用,我们将获取包含(1), (2), (2), (3)工作表,对其进行递归,生成 (2), (3), (3), (4),并将其附加到工作表。所以工作表现在应该(1), (2), (2), (3), (2), (3), (3), (4)。然而,结果开始于(1), (2), (2), (3), (3), (3), (4), (4)

谁能告诉我我的推理哪里出了问题?

最佳答案

您似乎混淆了 resultintermediate table,它们是不一样的。

(1), (2) 由“非递归”项生成并放置在结果中。
(1), (2) 也进入工作表
-- 在这里开始迭代
(2), (3) 由“递归”项生成并添加到结果
(2), (3) 也放在一个中间表中。
(2), (3)中间表的内容被移动到工作表
-- 迭代

正如手册在此处添加的那样 ( link to the current manual ):

Strictly speaking, this process is iteration not recursion, but RECURSIVE is the terminology chosen by the SQL standards committee.

与您的特定误解无关,只是为了解释我对“递归”的引用。

关于sql - 递归 CTE 如何与文档中的示例一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38192312/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com