为什么我看不到 CTE 中所做的更改?
Why don't I see changes done in CTE?
create table tab(id int);
insert into tab(id) values(1);
with x as (delete from tab where id = 1 returning id),
y as (select * from tab where id in (select id from x))
select * from y;
-- outputs a row with "1"
-- i need no rows returned
为什么我在 y
CTE 子查询中仍然看到已删除的行? x
和 y
部分应按顺序执行,因为 y
取决于 x
。您能否向我解释一下为什么我没有看到 x
的变化?我应该怎么做才能看到它们?
我不确定它是否与隔离级别有关,因为一切都是在同一个查询中完成的 => 同一个事务
谢谢!
该行为记录在 "7.8.2. Data-Modifying Statements in WITH
":
(...)
The sub-statements in WITH
are executed concurrently with each
other and with the main query. Therefore, when using data-modifying
statements in WITH
, the order in which the specified updates
actually happen is unpredictable. All the statements are executed with
the same snapshot (see Chapter
13), so they
cannot "see" one another's effects on the target tables. (...)
(...)
要从 table 中删除并在一个查询中使用 table 的架构获得空结果,只需在 CTE 中删除并从 table 中删除 select带有错误的 WHERE
子句。
WITH
cte
AS
(
DELETE FROM tab
WHERE id = 1
)
SELECT *
FROM tab
WHERE false;
create table tab(id int);
insert into tab(id) values(1);
with x as (delete from tab where id = 1 returning id),
y as (select * from tab where id in (select id from x))
select * from y;
-- outputs a row with "1"
-- i need no rows returned
为什么我在 y
CTE 子查询中仍然看到已删除的行? x
和 y
部分应按顺序执行,因为 y
取决于 x
。您能否向我解释一下为什么我没有看到 x
的变化?我应该怎么做才能看到它们?
我不确定它是否与隔离级别有关,因为一切都是在同一个查询中完成的 => 同一个事务
谢谢!
该行为记录在 "7.8.2. Data-Modifying Statements in WITH
":
(...)
The sub-statements in
WITH
are executed concurrently with each other and with the main query. Therefore, when using data-modifying statements inWITH
, the order in which the specified updates actually happen is unpredictable. All the statements are executed with the same snapshot (see Chapter 13), so they cannot "see" one another's effects on the target tables. (...)(...)
要从 table 中删除并在一个查询中使用 table 的架构获得空结果,只需在 CTE 中删除并从 table 中删除 select带有错误的 WHERE
子句。
WITH
cte
AS
(
DELETE FROM tab
WHERE id = 1
)
SELECT *
FROM tab
WHERE false;