查看关于 Sequence vs. Serial 的好答案。
Sequence 只会创建唯一数字的序列。它不是数据类型。这是一个序列。例如:
create sequence testing1;
select nextval('testing1'); -- 1
select nextval('testing1'); -- 2
您可以像这样在多个地方使用相同的序列:
create sequence testing1;
create table table1(id int not null default nextval('testing1'), firstname varchar(20));
create table table2(id int not null default nextval('testing1'), firstname varchar(20));
insert into table1 (firstname) values ('tom'), ('henry');
insert into table2 (firstname) values ('tom'), ('henry');
select * from table1;
| id | firstname |
|----|-----------|
| 1 | tom |
| 2 | henry |
select * from table2;
| id | firstname |
|----|-----------|
| 3 | tom |
| 4 | henry |
串行是一种伪数据类型。它将创建一个序列对象。让我们看一个简单的表格(类似于您将在链接中看到的表格)。
create table test(field1 serial);
这将导致与表一起创建一个序列。序列名称的命名法是<tablename>_<fieldname>_seq。上面的相当于:
create sequence test_field1_seq;
create table test(field1 int not null default nextval('test_field1_seq'));
另见:http://www.postgresql.org/docs/9.3/static/datatype-numeric.html
您可以重复使用由串行数据类型自动创建的序列,或者您可以选择每个表只使用一个序列/序列。
create table table3(id serial, firstname varchar(20));
create table table4(id int not null default nextval('table3_id_seq'), firstname varchar(20));
(这里的风险是如果table3被删除了,继续使用table3的序列,会报错)
create table table5(id serial, firstname varchar(20));
insert into table3 (firstname) values ('tom'), ('henry');
insert into table4 (firstname) values ('tom'), ('henry');
insert into table5 (firstname) values ('tom'), ('henry');
select * from table3;
| id | firstname |
|----|-----------|
| 1 | tom |
| 2 | henry |
select * from table4; -- this uses sequence created in table3
| id | firstname |
|----|-----------|
| 3 | tom |
| 4 | henry |
select * from table5;
| id | firstname |
|----|-----------|
| 1 | tom |
| 2 | henry |
请随意试用示例:http://sqlfiddle.com/#!15/074ac/1