在查询中多次使用 CTE
Use CTE multiple times in a query
我有以下查询
with cte as (
select
col1,
col2,
col3,
col4
from table
)
insert into table (col1,col2) select ct.co1,ct.col2 from cte ct
returning json_build_object(
'col1',col1,
'col2',col2,
'col3',ct.col3,
'col4',ct.col4
)
但是它的抛出错误
缺少 table“ct”的 FROM 子句条目
我听说 cte 可以在单个查询中多次使用,所以我相信这是可以实现的,
如何在不使用 temp table 的情况下实现此目的?
任何帮助,非常感谢。
谢谢
显然 returning
表达式在其自己的上下文中运行,因此它不会 'see' ct
。尝试这样的事情:
with cte as (
select
col1,
col2,
col3,
col4
from table_a
)
insert into table_b (col1, col2) select ct.col1, ct.col2 from cte ct
returning json_build_object(
'col1', col1,
'col2', col2,
'col3', (select cte.col3 from cte where cte.col1 = table_b.col1 and cte.col2 = table_b.col2),
'col4', (select cte.col4 from cte where cte.col1 = table_b.col1 and cte.col2 = table_b.col2)
);
我有以下查询
with cte as (
select
col1,
col2,
col3,
col4
from table
)
insert into table (col1,col2) select ct.co1,ct.col2 from cte ct
returning json_build_object(
'col1',col1,
'col2',col2,
'col3',ct.col3,
'col4',ct.col4
)
但是它的抛出错误 缺少 table“ct”的 FROM 子句条目
我听说 cte 可以在单个查询中多次使用,所以我相信这是可以实现的,
如何在不使用 temp table 的情况下实现此目的?
任何帮助,非常感谢。
谢谢
显然 returning
表达式在其自己的上下文中运行,因此它不会 'see' ct
。尝试这样的事情:
with cte as (
select
col1,
col2,
col3,
col4
from table_a
)
insert into table_b (col1, col2) select ct.col1, ct.col2 from cte ct
returning json_build_object(
'col1', col1,
'col2', col2,
'col3', (select cte.col3 from cte where cte.col1 = table_b.col1 and cte.col2 = table_b.col2),
'col4', (select cte.col4 from cte where cte.col1 = table_b.col1 and cte.col2 = table_b.col2)
);