为什么这个 CTE 就像一个计数器? [英] Why does this CTE act like a counter?

查看:27
本文介绍了为什么这个 CTE 就像一个计数器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下查询的行为与我对 CTE 的理解不同,有人可以详细说明为什么会这样吗?

The behaviour of the following query is different from my understanding of CTE, can someone elaborate why this is so?

with cte (n) as
(
    select 1
    union all
    select n + 1 from cte where n<10
)
select * from cte

我期待以下输出:

1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10

但我得到:

1,2,3,4,5,6,7,8,9,10

为什么?

推荐答案

CTE 基本上是一个可重用的子查询,可以引用自身,因此您的最终查询等效于:

A CTE is basically a re-usable sub-query that can refer to itself, so your final query is equivalent to:

SELECT 1
UNION ALL (SELECT 2 
           UNION ALL (SELECT 3 ...

直到 n 达到 10.

这篇关于为什么这个 CTE 就像一个计数器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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