通过 PostgreSQL 唯一地插入数据库
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1244271/
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
To INSERT INTO a database uniquely by PostgreSQL
提问by Léo Léopold Hertz ??
My table
我的桌子
question_id | title | user_id |
+---------------+---------------------------------+----------------+
Its types are
它的类型是
Column | Type | Modifiers
---------------------------------------+-----------------------------+-----------------------------------------------------------------
question_id | integer | not null default nextval('questions_question_id_seq'::regclass)
title | character varying(256) |
user_id | integer |
I run
我跑
INSERT INTO questions VALUES (SERIAL, 'question title', 123);
I get an error about the use of SERIAL.
我收到关于使用 SERIAL 的错误。
How can you add the question to the table automatically taking an unique question_id by PostgreSQL?
PostgreSQL 如何自动将问题添加到表中,并采用唯一的 question_id?
回答by Pablo Santa Cruz
DEFAULT VALUE you have will auto generate a (serial) number from a sequence that's on your DataBase. So you can just do a simple:
您拥有的默认值将从您的数据库上的序列自动生成一个(序列)编号。所以你可以做一个简单的:
insert into questions (title, user_id) values ('question_title', 123);
It will insert an AUTO INCREMENTED number in question_idfield because of ** questions_question_id_seq** sequence.
由于 ** questions_question_id_seq** 序列,它将在question_id字段中插入一个 AUTO INCREMENTED 数字。
Alternatively, instead of using SERIAL, on your insert clause, you could also use the sequence. But I would rather use the first sentence I suggested:
或者,您也可以在插入子句上使用序列,而不是使用 SERIAL。但我宁愿使用我建议的第一句话:
insert into questions values (nextval('questions_question_id_seq'), 'question_title', 123);
回答by Andrejs Cainikovs
Normally, you don't need to specify the unique id, as this is done server-side. You should use following:
通常,您不需要指定唯一 ID,因为这是在服务器端完成的。您应该使用以下内容:
INSERT INTO questions (title, user_id) VALUES ('question title', 123);
Automatic id handling is done by 'questions_question_id_seq' sequence as you may see in modifier section.
自动 id 处理由“questions_question_id_seq”序列完成,您可以在修饰符部分看到。
回答by asb
You can also create table using
您还可以使用创建表
Create Table tbl_1 ( id SERIAL , name varchar(30));
You can go on inserting data like
您可以继续插入数据,例如
insert into tbl_1(name) values('xyz');
This will create the id automatically. Using Serial is equivalent to the sequence only. You can check link text
这将自动创建 ID。使用 Serial 仅等效于序列。您可以检查链接文本