如果 id 字段上有主键,如何在 table 中插入值?

How to insert values in table if there is a primary key on id field in it?

我有麻烦了,我有 table 名为 my_table)

id name
1 A
2 B
3 C

我想插入前 2 个值,因此值会像这样自动递增

insert into my_table (name) values (A), (B); 

这在 postgressql 中可行吗?

可能我应该有 count() + 1,然后在这里有 count() + 2

insert into my_table (id, name) values (count(*) + 1, A), (count(*) + 2, B);

或类似这样的东西 因为我的id有约束

BIGSEREIAL PRIMARY KEY NOT NULL

而且我无法在没有获取 table 中的最后一个 ID 的情况下添加值。

你可以这样做:

create table my_table (
  id int not null generated always as identity,
  name varchar(10) not null
);

insert into my_table (name) values ('A'), ('B');

然后:

select * from my_table;

结果:

id  name
--  ----
 1  A   
 2  B   

参见 db<>fiddle 中的 运行 示例。