为什么使用数字表比使用递归 CTE 动态生成它们要快得多?
numbers在我的机器上,给定一个包含 1 到 100000 数字的单列(主键)的表n,查询如下:
select n from numbers;
Run Code Online (Sandbox Code Playgroud)
大约需要 400 毫秒才能完成。
使用递归 CTE 生成数字 1 到 100000:
with u as (
select 1 as n
union all
select n + 1
from u
where n < 100000
)
select n
from u
option(maxrecursion 0);
Run Code Online (Sandbox Code Playgroud)
在 SQL Server 2019 上大约需要 900 毫秒才能完成。
我的问题是,为什么第二个选项比第一个选项慢这么多?第一个不是从磁盘获取结果,因此应该更慢吗?
否则有什么办法可以让CTE跑得更快吗?因为在我看来,这是比在数据库中存储数字列表更优雅的解决方案。