如果我们插入一笔记录,我们希望系统自动为我们分配一个ID,那么我们需要使用serial type。如果我们创建表的时候,自动创建一个serial类型(包smallserial and bigserial),系统会自动帮我们创建sequence这种数据库对象。
createtable employ(
id serial,
name varchar(64),
department varchar(64)
);
manu_db=# create table employ(id serial,name varchar(64),department varchar(128)) ;
NOTICE: CREATE TABLE will create implicit sequence "employ_id_seq" for serial column "employ.id"
CREATE TABLE
manu_db=# \d
List of relations
Schema | Name | Type | Owner
--------+---------------+----------+-------
public | employ | table | manu
public | employ_id_seq | sequence | manu
(2 rows)
manu_db-# \d employ
Table "public.employ"
Column | Type | Modifiers
------------+------------------------+-----------------------------------------------------
id | integer | not null default nextval('employ_id_seq'::regclass)
name | character varying(64) |
department | character varying(128) |
manu_db=# create table employ_copy (like employ) ;
CREATE TABLE
manu_db=# \d employ_copy
Table "public.employ_copy"
Column | Type | Modifiers
------------+------------------------+-----------
id | integer | not null
name | character varying(64) |
department | character varying(128) |
manu_db=# \d employ
Table "public.employ"
Column | Type | Modifiers
------------+------------------------+-----------------------------------------------------
id | integer | not null default nextval('employ_id_seq'::regclass)
name | character varying(64) |
department | character varying(128) |
manu_db=#
如果业务需要,创建一个schema和employ一模一样的table,我们只能够用like,但是,我们看到,id这个字段并不完全一样,原因就是没有sequence和新建的table对应。这种情况,我们有没有办法,事后创建sequence,建立table中id字段的联系, I mean id use nextval as default?
答案是肯定的:
CREATESEQUENCE employ_copy_id_seq ;
ALTERTABLE employ_copy ALTERCOLUMN id SETDEFAULT nextval('employ_copy_id_seq');
ALTER SEQUENCE employ_copy_id_seq OWNED by employ_copy.id ;
看看效果:
manu_db=# CREATE SEQUENCE employ_copy_id_seq ;
CREATE SEQUENCE
manu_db=# ALTER TABLE employ_copy ALTER COLUMN id SET DEFAULT nextval('employ_copy_id_seq');
ALTER TABLE
manu_db=# \d employ_copy
Table "public.employ_copy"
Column | Type | Modifiers
------------+------------------------+----------------------------------------------------------
id | integer | not null default nextval('employ_copy_id_seq'::regclass)
name | character varying(64) |
department | character varying(128) |
注意,加了alter sequence owned by ,在删除table的时候,会自动的将sequence删掉。如果不建立这种owned by的关系,删除table,不会引发sequence被删除。我就不贴了,可以自己try。