PostgreSQL:插入链抛出“列不存在”

xt0899hw  于 2022-12-18  发布在  PostgreSQL
关注(0)|答案(1)|浏览(137)

我有一个函数,可以在第一个表中为每个输入行插入一行,并在第二个表中用第一个插入的id链接两行。

begin
    with participants as(
      select (first, second)
      from get_contest_participants_candidates(competition_id_input)
    ), new_contest as(
      insert into contests (competition_id)
      select competition_id_input
      from participants
      returning id
    ) 
    insert into "contestParticipants" (contest_id, contestant_id)
    values(
      (select c.id, p.first from new_contest c, participants p),
      (select c.id, p.second from new_contest c, participants p)
    );
  end;

函数get_contest_participants_candidates()返回
| 第一|秒|
| - ------|- ------|
| 1个|第二章|
| 1个|三个|

预期成果:

contests
| 身份证|竞争标识|
| - ------|- ------|
| 1个|1个|
| 第二章|1个|
contestParticipants
| 身份证|竞赛标识|参与者ID|
| - ------|- ------|- ------|
| 1个|1个|1个|
| 第二章|1个|第二章|
| 三个|第二章|1个|
| 四个|第二章|三个|
但它的回报是:

Failed to run sql query: column "first" does not exist

如果将(first, second)更改为first, second,则返回

Failed to run sql query: subquery must return only one column


我做错什么了?

thtygnil

thtygnil1#

您在这里有不正确的语法:

insert into "contestParticipants" (contest_id, contestant_id)
    values(
      (select c.id, p.first from new_contest c, participants p),
      (select c.id, p.second from new_contest c, participants p)
    );

也许你想这样写:

insert into "contestParticipants" (contest_id, contestant_id)
      select c.id, p.first from new_contest c, participants p
      union all
      select c.id, p.second from new_contest c, participants p;

相关问题