英文:
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('my_table_id_seq'::regclass));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论