postgres CTE 中的多个更新语句

Multiple update statements in postgres CTE

我遇到了一个包含多个更新语句的 CTE 表达式的奇怪问题。

我可以使用以下内容进行重现 SQL:-

DROP TABLE IF EXISTS foo;
DROP TABLE IF EXISTS baa;
CREATE TABLE foo(id BIGSERIAL, attributes JSONB);
CREATE TABLE baa(id BIGSERIAL, attributes JSON );
INSERT  INTO foo(attributes) SELECT jsonb_build_object('foo', 'baa');

WITH STEP_ONE AS (

    UPDATE foo 
    SET attributes = attributes ||jsonb_build_object('foo2', 'baa2')
    WHERE id = 1
    RETURNING attributes->>'foo' AS foo_att,id

), STEP_TWO AS (
    INSERT INTO baa(attributes)
    SELECT json_build_object('foo', id)
    FROM STEP_ONE
    RETURNING id as baa_id
) 
UPDATE foo
  SET attributes = attributes ||jsonb_build_object('baa', baa_id)
  FROM STEP_TWO
  WHERE id = 1

这不会更新 table foo。但是用 "SELECT * FROM STEP_TWO" 替换最终更新表明存在记录。

这是 postgresql 中的错误吗?还是我在文档中遗漏了有关在 CTE 中多次更新单个 table 的内容?

Postgres 版本:

PostgreSQL 11.4 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.3 20140911 (Red Hat 4.8.3-9), 64-bit

是的,这个is documented:

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 在语句中只修改一次,要么您必须 运行 两个单独的语句。