postgresql 如何在插入过程中指定本机表字段和外表字段?

k5ifujac  于 2023-02-22  发布在  PostgreSQL
关注(0)|答案(1)|浏览(163)

假设如下:

create table member (
    id serial primary key,
    member_name varchar(55),
    role_ids bigint[] not null
);

create table role (
    id serial primary key,
    role_name varchar(55) unique
);

insert into role values (1, 'admin'), (2, 'common');

我可以像这样创建一个admin member

insert into member (role_ids)
select ARRAY[id] as role_id from role where role_name = 'admin';

但是如何指定其他字段,比如member_name
我试过这个:

insert into member (member_name, role_ids) values('test member', role_ids)
select ARRAY[id::bigint] as role_id from role where role_name = 'admin';

但这会引发错误error at or near select

iaqfqrcu

iaqfqrcu1#

在您的情况下,我可能会选择在VALUES中使用嵌套的SELECT,以强调这是一个您期望成功并且只返回一个值的查找:

insert into member (member_name, role_ids)
values('test member',
    (select ARRAY[id] from role where role_name = 'admin'));

如果你在select中选择了多列,这就不起作用了,另一个解决方案是只使用SELECT而不使用VALUES,因为没有什么可以阻止你在SELECT中返回文字值,你不需要在select中为insert命名列,而是按照insert中列的顺序排列它们:

insert into member (member_name, role_ids)
select 'test member', ARRAY[id] from role where role_name = 'admin';

相关问题