【发布时间】:2021-11-01 08:42:43
【问题描述】:
我在 Postgres 中有一个表 table_1,其中包含基于 Django 模型的三列,ID(自动递增值)、affiliation 和 entry。
我需要做的是获取affiliation = 52 所在的每个条目,然后添加带有entry = query.entry 和affiliation = 48 的附加行。我需要额外的行,而不是更改值。我还需要确保 entry + affiliation 对不存在。
我最近的尝试:
do $$
declare
id_array int[];
begin
insert into id_array table_1.entry where table_1.affiliation = 52;
for id in id_array
loop
if not exists (select entry from table_1 where affiliation = 48)
then
insert into table_1 (affiliation, entry) values (48, id);
else
raise notice "already exists";
end if;
endloop;
end; $$
我仍然遇到语法错误!有任何想法吗?我完全不知所措。这是迄今为止我尝试过的最复杂的查询。
【问题讨论】:
-
将语法错误添加到您的问题中。虽然我要说问题就在这里:
insert into id_array ...。如果我没听错,那可能应该是:select into id_array array_agg(entry) from table1 where affiliation = 52;
标签: sql django postgresql unique-constraint upsert