SQL 中的递归 [英] RECURSIVE in SQL

查看:41
本文介绍了SQL 中的递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 SQL 并且很难理解以下递归 SQL 语句.

I'm learning SQL and had a hard time understanding the following recursive SQL statement.

WITH RECURSIVE t(n) AS (
    SELECT 1
    UNION ALL
    SELECT n+1 FROM t WHERE n < 100
)
SELECT sum(n) FROM t;

SELECT sum(n) FROM t; 中的 n 和 t 是什么?据我所知,n 是一个数,t 是一个集合.我说得对吗?

What is n and t from SELECT sum(n) FROM t;? As far as I could understand, n is a number of t is a set. Am I right?

还有这个语句中的递归是怎么触发的?

Also how is recursion triggered in this statement?

推荐答案

您使用的语法看起来像 Postgres.SQL 中的递归"并不是真正的递归,而是迭代.您的陈述是:

The syntax that you are using looks like Postgres. "Recursion" in SQL is not really recursion, it is iteration. Your statement is:

WITH RECURSIVE t(n) AS (
    SELECT 1
    UNION ALL
    SELECT n+1 FROM t WHERE n < 100
)
SELECT sum(n) FROM t;

t 的语句被评估为:

  1. 评估非自引用部分(select 1).
  2. 然后评估自我引用部分.(最初这给出了 2.)
  3. 然后再次评估自引用部分.(3).
  4. 依此类推,条件仍然有效(n <100).

完成后,t 子查询就完成了,可以评估最终语句.

When this is done the t subquery is finished, and the final statement can be evaluated.

这篇关于SQL 中的递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆