我跑
SELECT *
FROM
(SELECT
*,
ROW_NUMBER() OVER () AS n
FROM
{table_name}) t
WHERE
n < 10000
Run Code Online (Sandbox Code Playgroud)
在 Postgres 中。我注意到每次运行的结果都不同。
为了测试除了顺序之外内容是否不同,我对列进行了平均。结果很有趣:有主键的表的返回值是一致的,而另一个没有主键的表在每次运行中都不同。
具有PK的表的执行计划:
"Aggregate (cost=139391585.22..139391585.23 rows=1 width=32)"
" -> WindowAgg (cost=0.58..99288350.02 rows=3208258816 width=9090)"
" Run Condition: (row_number() OVER (?) < 10000)"
" -> Index Only Scan using mea_vit_pi_4221ef4deeadcabf_ix on {table_name} (cost=0.58..59185114.82 rows=3208258816 width=8)"
Run Code Online (Sandbox Code Playgroud)
没有pk的表的执行计划:
"Aggregate (cost=83580303.64..83580303.65 rows=1 width=32)"
" -> WindowAgg (cost=0.00..61837074.84 rows=1739458304 width=650)"
" Run Condition: (row_number() OVER (?) < 10000)"
" -> Seq Scan on {table_2} (cost=0.00..40093846.04 rows=1739458304 …Run Code Online (Sandbox Code Playgroud)