PostgreSQL插入具有单列主键的自增表

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

Postgres INSERT INTO autoincrement table with single column primary key

问题

我试图自动增加一个只有一个主键列的表,例如:

CREATE TABLE my_table (id PRIMARY KEY NOT NULL);

通常情况下,为了自动增加它,我会在插入语句中不包括主键列,但在只有一个列的情况下似乎不可行。以下操作会导致“语法错误,附近或在“)”附近”的错误:

INSERT INTO my_table () VALUES ();
英文:

I am trying to auto increment a table with a single column which is a primary key, eg:

CREATE TABLE my_table (id PRIMARY KEY NOT NULL);

I would usually just not include the primary key column in the insert statment in order to autoincrement it, but this doesn't seem possible in the case where there is only a single column. The below results in "syntax error at or near \")\""

INSERT INTO my_table () VALUES ();

答案1

得分: 1

将您的列定义为身份,然后在插入时指定关键字DEFAULT。

创建表dumb_id(id integer generated always as identity primary key);
插入到dumb_id(id)的值为(default);

注意:不需要在default周围使用引号。演示在此处 <br/>
但是这样的表有什么意义呢?

英文:

Define your column as an identity then on insert specify the keyword DEFAULT.

create table dumb_id ( id   integer  generated always as identity primary key); 
insert into dumb_id (id) values (default);

Note: You do not use quotes around default. Demo here <br/>
But what is the point of such a table?

答案2

得分: 0

你可以在插入时将 id 的值设置为 Auto Value
示例:

创建表 my_table(id Serial PRIMARY KEY NOT NULL);
插入数据到 my_table(id) VALUES( nextval('my_table_id_seq'::regclass));
英文:

You can set value of id = Auto Value when insert
Ex:

CREATE TABLE my_table (id Serial PRIMARY KEY NOT NULL);
INSERT INTO my_table(id) VALUES( nextval(&#39;my_table_id_seq&#39;::regclass));

huangapple
  • 本文由 发表于 2023年6月5日 09:21:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76403043.html
匿名

发表评论

匿名网友

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

确定