Sql 如何自动增加id并插入2行
我有两个一对一关系的表,我想用相同的自动递增id向表中插入两行。可以吗Sql 如何自动增加id并插入2行,sql,postgresql,select,sql-insert,Sql,Postgresql,Select,Sql Insert,我有两个一对一关系的表,我想用相同的自动递增id向表中插入两行。可以吗 create table first ( id bigint primary key, value varchar(100) not null ); create table second ( id bigint references first (id), sign boolean ); insert into first(id, value) values (-- auto
create table first
(
id bigint primary key,
value varchar(100) not null
);
create table second
(
id bigint references first (id),
sign boolean
);
insert into first(id, value)
values (-- autoincremented, 'some_value');
insert into second(id, sign)
values (-- the same autoincremented, true);
一个选项使用带有
返回
子句的cte:
with i as (
insert into first(value) values('some_value')
returning id
)
insert into second(id, sign)
select i.id, true from i
这将同时执行两个插入;自动生成第一次插入的id
,然后在第二次插入中使用
为此,您需要将
第一个
表的id
定义为串行
一个选项使用带有返回
子句的cte:
with i as (
insert into first(value) values('some_value')
returning id
)
insert into second(id, sign)
select i.id, true from i
这将同时执行两个插入;自动生成第一次插入的id
,然后在第二次插入中使用
要使其工作,您需要将
第一个
表的id
定义为serial
必须将id
列定义为“自动递增”列,然后才能使用该列:
create table first
(
id bigint generated always as identity primary key,
value varchar(100) not null
);
然后可以使用lastval()
获取最后生成的id:
insert into first(id, value)
values (default, 'some_value');
insert into second(id, sign)
values (lastval(), true);
或者,如果您希望明确:
insert into first(id, value)
values (default, 'some_value');
insert into second(id, sign)
values (currval(pg_get_serial_sequence('first','id')), true);
必须将
id
列定义为“自动递增”列,然后才能使用该列:
create table first
(
id bigint generated always as identity primary key,
value varchar(100) not null
);
然后可以使用lastval()
获取最后生成的id:
insert into first(id, value)
values (default, 'some_value');
insert into second(id, sign)
values (lastval(), true);
或者,如果您希望明确:
insert into first(id, value)
values (default, 'some_value');
insert into second(id, sign)
values (currval(pg_get_serial_sequence('first','id')), true);
谢谢你的回复。使用with插入几对是正常的吗?@Vlad:是的,在Postgres中也可以(你可以看到),谢谢你的回复。使用with插入几对是正常的吗?@Vlad:是的,在Postgres中也可以(你可以看到)@a_uuu非常感谢。你能写下如何插入几行吗?可能吗?@非常感谢。你能写下如何插入几行吗?可能吗?