微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Postgresql 创建主键并设置自动递增的三种方法

Postgresql 有以下三种方法设置主键递增的方式,下面来看下相同点和不同点。

--方法
create table test_a
(
id serial,
name character varying(128),
constraint pk_test_a_id primary key( id)
);

NOTICE: CREATE TABLE will create implicit sequence "test_a_id_seq" for serial column "test_a.id"
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "pk_test_a_id" for table "test_a"
CREATE TABLE


--方法
create table test_b
(
id serial PRIMARY KEY,
name character varying(128)
);

NOTICE: CREATE TABLE will create implicit sequence "test_b_id_seq" for serial column "test_b.id"
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "test_b_pkey" for table "test_b"
CREATE TABLE


--方法
create table test_c
(
id integer PRIMARY KEY,
name character varying(128)
);
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "test_c_pkey" for table "test_c"
CREATE TABLE


CREATE SEQUENCE test_c_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;

alter table test_c alter column id set default nextval('test_c_id_seq');


很明显从上面可以看出,方法一和方法二只是写法不同,实质上主键都通过使用 serial 类型来实现的,
使用serial类型,PG会自动创建一个序列给主键用,当插入表数据时如果不指定ID,则ID会认使用序列的
NEXT值。

方法三是先创建一张表,再创建一个序列,然后将表主键ID的认值设置成这个序列的NEXT值。这种写法
似乎更符合人们的思维习惯,也便于管理,如果系统遇到sequence 性能问题时,便于调整 sequence 属性

--比较三个表的表结构 skytf=> \d test_a Table "skytf.test_a" Column | Type | Modifiers --------+------------------------+----------------------------------------------------- id | integer | not null default nextval('test_a_id_seq'::regclass) name | character varying(128) | Indexes: "pk_test_a_id" PRIMARY KEY,btree (id) skytf=> \d test_b Table "skytf.test_b" Column | Type | Modifiers --------+------------------------+----------------------------------------------------- id | integer | not null default nextval('test_b_id_seq'::regclass) name | character varying(128) | Indexes: "test_b_pkey" PRIMARY KEY,btree (id) skytf=> \d test_c Table "skytf.test_c" Column | Type | Modifiers --------+------------------------+----------------------------------------------------- id | integer | not null default nextval('test_c_id_seq'::regclass) name | character varying(128) | Indexes: "test_c_pkey" PRIMARY KEY,btree (id) 从上面可以看出,三个表表结构一模一样, 三种方法如果要寻找差别,可能仅有以下一点, 当 drop 表时,方法一和方法二会自动地将序列也 drop 掉,而方法三不会。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐