如何在插入时指定本地表字段和外部表字段?

huangapple go评论41阅读模式
英文:

How to specify native table fields and a foreign table field during an insert?

问题

以下是要翻译的内容:

Suppose the following:

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');

I can create an admin member like this:

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

But how can I specify other fields, like member_name as well?

I've tried this:

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';

But this throws an error, error at or near select.

英文:

Suppose the following:

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');

I can create an admin member like this:

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

But how can I specify other fields, like member_name as well?

I've tried this:

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';

But this throws an error, error at or near select

答案1

得分: 1

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

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

如果你在选择中选择多个列,这种方法就不起作用。另一种解决方案是只使用 SELECT 而不使用 VALUES,因为在你的 SELECT 中返回文字值是没有问题的。你不需要为插入中的选择命名列,而是按照插入中列的顺序进行排序:

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

In your case I would probably choose to use a nested SELECT inside the VALUES, to emphasize that this is a lookup that you expect to succeed and return only one value:

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

This wouldn't work if you were selecting more than one column in your select. Another solution would be to just use SELECT and no VALUES, because nothing stops you from returning literal values in your SELECT. You don't name the columns in the select for your insert, instead you order them to match the order of the columns in the insert:

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

huangapple
  • 本文由 发表于 2023年2月19日 21:19:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75500417.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定