有条件地根据 SELECT 执行 INSERT 导致 postgres sql 函数

Conditionally do INSERT based on SELECT result in postgres sql function

如何根据另一个 table 是否有值对 table 执行 INSERT?这是一个例子

create table mygroup (
  group_id integer primary key,
  other_id integer not null references othertable(other_id)
);

create table myitem (
  group_id integer not null references mygroup(group_id),
  item_id integer not null
);

create function add_to_group (group_arg integer, item_arg integer, other_arg integer) language sql as $$
  select * from mygroup where group_id = group_arg and other_id = other_arg;
  -- Do the next statement only if the previous one had a result
  insert into myitem (group_id, item_id) values (group_arg, item_arg);
$$;

如果我使用的是 plpgsql 函数,则可以使用 if (found) 来实现。但是我怎样才能使用普通的 sql 函数呢?有没有办法将两个语句合并为一个语句,例如用 JOIN 执行 INSERT?

我想你只是想要 exists:

insert into myitem (group_id, item_id) 
    select v.group_id, v.item_id
    from (values (group_arg, item_arg)) v(group_id, item_id)
    where exists (select 1
                  from mygroup g
                  where g.group_id = v.group_id and v.other_id = other_arg
                 );

或者,您可以使用 select 如果 mygroup table 中只有一行应该匹配:

insert into myitem (group_id, item_id) 
    select group_arg, item_arg
    from mygroup g
    where g.group_id = group_arg and v.other_id = other_arg;

如果可能出现重复,您可以将其调整为:

insert into myitem (group_id, item_id) 
    select distinct group_arg, item_arg
    from mygroup g
    where g.group_id = group_arg and g.other_id = other_arg;