Refactor functions so they can be used within a CTE

后端 未结 1 2011
一生所求
一生所求 2021-01-20 21:57

I have a parent and child table as following:

create table parent
(
  identifier serial primary key,
  name text
);
create table ch         


        
相关标签:
1条回答
  • 2021-01-20 22:41

    As you noticed correctly, you cannot see rows modified in the CTE in the main SELECT. This is documented:

    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. This alleviates the effects of the unpredictability of the actual order of row updates, and means that RETURNING data is the only way to communicate changes between different WITH sub-statements and the main query.

    So you should use RETURNING.

    I guess the simplest way would be not to use a function, but to perform json_build_object in the main query and have it operate on the CTEs parents and children.

    0 讨论(0)
提交回复
热议问题