Postgres:在脚本的另一个查询中使用返回值



我在docker容器中运行postgres。我使用卷挂载使用SQl文件加载初始数据。

我需要运行第一个查询在ORG_ORGANISATION表中创建一行。我使用"返回";输出创建的组织ID。

当我试图在另一个插入查询中使用返回值时,我得到以下错误:

2022-07-09 05:30:54.768 UTC [52] ERROR: column "字符91不存在2022-07-09 05:30:54.768 UTC[52]提示:有一个专栏叫"org_id"在表"org_entity"中,但不能从查询的这一部分引用它。[52]语句:insert into org_entity (org_id, parent_entity_id, name, display_name, description)值(org_id, org_id, "Asia Pacific region "APAC" region of APAC"),(org_id, org_id, "Region of european, Middle East and Africa" "EMEA" "Region of EMEA"),

INSERT INTO ORG_ORGANISATION (NAME, DISPLAY_NAME, DESCRIPTION ) VALUES('TestOrg', 'Green Tech Services', 'An organization committed to measure GHG emissions and reduce GHG emissions')
RETURNING org_id; 
INSERT INTO ORG_ENTITY(ORG_ID, PARENT_ENTITY_ID, NAME, DISPLAY_NAME, DESCRIPTION)
VALUES
(org_id, org_id, "Asia Pacific Regiion", "APAC", "Regiion of APAC"),
(org_id, org_id, "Region of Europe, Middle East and Africa", "EMEA", "Regiion of EMEA"),
(org_id, org_id, "Region of Americas", "AMERICAS", "Regiion of AMERICAS");

谁能帮我去掉这个错误?

提前感谢。

需要使用数据修改公共表表达式将两个insert合并为一个insert。您还需要对字符串常量使用单引号。"APAC"是标识符,例如列名。'APAC'是一个字符串常量。

with new_org as (
insert into org_organisation 
(name, display_name, description ) 
values
('TestOrg', 'Green Tech Services', 'An organization committed to measure GHG emissions and reduce GHG emissions')
returning org_id
)  
insert into org_entity(org_id, parent_entity_id, name, display_name, description)
select o.org_id, o.org_id, v.name, v.display_name, v.description
from new_org o
cross join ( 
values
('Asia Pacific Regiion', 'APAC', 'Regiion of APAC'),
('Region of Europe, Middle East and Africa', 'EMEA', 'Regiion of EMEA'),
('Region of Americas', 'AMERICAS', 'Regiion of AMERICAS')
) as v(name, display_name, description);

由于插入到org_organisation只返回单行,因此交叉连接不会生成比values子句中指定的更多的行

这是两个独立的语句——为什么一个语句能够看到另一个语句呢?您需要将其合并到单个查询中。

WITH new_row AS (
INSERT INTO ...
RETURNING org_id
)
INSERT INTO org_entity (...)
SELECT new_row.org_id, 'blah', 'blah', 'blah' FROM new_row
UNION ALL
SELECT new_row.org_id, 'blah2', 'blah2', 'blah2' FROM new_row
UNION ALL
...
;

您可以将值放入另一个子查询中,并针对单个新id执行交叉连接,但这可能更容易理解。

你可能也想读一些SQL的入门指南来掌握作用域、语句和事务等等。

最新更新