如何根据另一个表是否有值来对表执行插入操作?下面是一个例子
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?
发布于 2020-04-21 18:50:36
我想你只是想要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;https://stackoverflow.com/questions/61341721
复制相似问题