postgresql 插入语句要求我为自动增量列插入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15464852/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert statement asked me to insert for autoincrement column
提问by Aan
I use PostgreSQL, I have created the following table:
我使用 PostgreSQL,我创建了下表:
CREATE TABLE "Task"
(
"taskID" serial NOT NULL,
"taskType" text NOT NULL,
"taskComment" text NOT NULL,
"taskDate" date NOT NULL,
CONSTRAINT "Task_pkey" PRIMARY KEY ("taskID")
)
I put taskID as serial
data-type to be incremented automatically. Now I am confused how to use the INSERT
statement, as the first column in the table is supposed to increment automatically but INSERT
statement asked me to insert a value by myself! Any Idea?
我将 taskID 作为serial
要自动递增的数据类型。现在我很困惑如何使用该INSERT
语句,因为表中的第一列应该自动递增,但 INSERT
语句要求我自己插入一个值!任何的想法?
Here is my insert statement:
这是我的插入语句:
INSERT INTO "Task" VALUES ('HomeWork', 'No Comment', '3/3/2013');
回答by Erwin Brandstetter
@mvp's answercovers this pretty much. Except for the case where you (have to) add the id
column in the column list for some reason. Then you can use the key word DEFAULT
to default to the defined default value. Yeah, lots of "default" in this sentence, but it should be correct. :)
@mvp 的回答几乎涵盖了这一点。除了出于id
某种原因您(必须)在列列表中添加列的情况。然后你可以使用关键字DEFAULT
来默认为定义的默认值。是的,这句话中有很多“默认”,但它应该是正确的。:)
INSERT INTO "Task"("taskID", "taskType", "taskComment", "taskDate")
VALUES (DEFAULT, 'HomeWork', 'No Comment', '2013-03-03');
You'd also better use ISO 8601 date format (YYYY-MM-DD
), which works independent of locale settings. Your regionally valid format is prone to breakage.
您还最好使用 ISO 8601 日期格式 ( YYYY-MM-DD
),它独立于区域设置。您的区域有效格式容易损坏。
However, if you distance yourself from the folly to use mixed case identifiersto begin with, your life in PostgreSQL will be much simpler:
但是,如果您远离使用混合大小写标识符的愚蠢做法,那么您在 PostgreSQL 中的生活将简单得多:
CREATE TABLE task (
task_id serial NOT NULL PRIMARY KEY,
task_type text NOT NULL,
task_comment text NOT NULL,
task_date date NOT NULL
);
INSERT INTO task
VALUES (DEFAULT, 'HomeWork', 'No Comment', '2013-03-03');
Or better:
或者更好:
INSERT INTO task (task_type, task_comment, task_date)
VALUES ('HomeWork', 'No Comment', '2013-03-03');
回答by mvp
You should NOTlist this auto-incremented column in INSERT
statement, and it will work as you expect:
你应该不列出该自动递增的列INSERT
语句,因为你希望它会工作:
INSERT INTO "Task" (
"taskType", "taskComment", "taskDate"
) VALUES (
'abc', 'my comment', '2013-03-17'
)
If you DO list it in INSERT
, you will have to make sure that provided value does not conflict with any used values - which in general will be difficult to satisfy, unless you consistently use nextval('some_sequence')
.
如果您INSERT
确实将其列在nextval('some_sequence')
.