[英]Conditionally do INSERT based on SELECT result in postgres sql function
如何根据另一个表是否有值对表执行 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 function ,则可以使用if (found)
来完成。 但是如何使用普通的 sql function 来做到这一点? 有没有办法将两个语句合并为一个,例如使用 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
);
或者,如果mygroup
表中只有一行应该匹配,您可以使用select
:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.