[英]Update isn't working using with clause
WITH first_insert AS
(
INSERT INTO first_insert_table (column_of_first_insert_table)
VALUES (10)
RETURNING first_insert_table_id
),
second_insert AS
(
INSERT INTO second_insert_table(column_of_second_insert_table)
VALUES((SELECT * FROM first_insert))
RETURNING second_insert_table_id
)
--here doesn't update column_of_first_insert_table!
UPDATE first_insert_table
SET column_of_first_insert_table = column_of_first_insert_table + 1
WHERE first_insert_table_id = (SELECT * FROM first_insert) ;
当我尝试更新first_insert_table
表时,为什么此查询不更新first_insert_table
column_of_first_insert_table
列?
无法执行预期更新的原因与示例的简化版本不会显示在WITH
子句中插入的行的原因相同:
with cte as (
insert into first_insert_table (column_of_first_insert_table)
values (10)
)
select * from first_insert_table
执行上面的语句时, INSERT
确实成功发生,但是该SELECT
部分看不到它,因为SELECT
仅看到该语句开始执行时存在的数据。
您的示例中也发生了同样的情况。 UPDATE
的WHERE
子句只能找到整个语句开始时存在的行,因此看不到在WITH
子句中插入的行。
这种行为被记录在案( 7.8.2在修改数据的语句。 WITH
):
WITH
中的子语句彼此并与主查询并发执行。 因此,在WITH
使用数据修改语句时,指定更新实际发生的顺序是不可预测的。 所有语句都使用相同的快照执行(请参见第13章),因此它们无法“看到”彼此对目标表的影响。 这减轻了行更新实际顺序的不可预测性的影响,并且意味着RETURNING
数据是在不同的WITH
子语句与主查询之间传递更改的唯一途径。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.