是否有可能在READ COMMITTED隔离级别的CTE子句中有不同的结果?

时间:2017-12-31 09:24:54

标签: sql postgresql

read committed隔离级别,同一事务中的2个后续选择查询可能会有不同的结果,因为两个查询之间可能有并发更新:

transaction 1: select id from table;
    => returns [1, 2, 3]
transaction 2: delete from table where id = 2;
transaction 1: select id from table;
    => returns [1, 3]

如果事务1中的选择查询在CTE中组合会发生什么?假设我有以下虚拟查询:

with
cte_1 as (select id from table),
cte_2 as (select id from table)
select (select count(*) from cte_1, select count(*) from cte_2)

如果在执行cte_1cte_2之间发生并发更新,我们现在是否也可能得到不同的结果?

1 个答案:

答案 0 :(得分:4)

每个语句都以原子方式执行,并在整个运行时期间看到数据库的一致视图。 “两个CTE”是单个查询,因此查询在运行时也看不到任何(已提交的)更改

CTE查询相当于:

select (select count(*) from (select id from table) as cte1), 
       (select count(*) from (select id from table) as cte2)

无关,但是:您可能不知道select (a,b)在Postgres中有所不同select a,b。第一个返回一个具有匿名记录类型(具有两个字段)的列,第二个返回两列。