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

前端之家收集整理的这篇文章主要介绍了Postgresql 创建主键并设置自动递增的三种方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

--方法

  1. create table test_a
  2. (
  3. id serial,name character varying(128),constraint pk_test_a_id primary key( id)
  4. );
  5.  
  6. NOTICE: CREATE TABLE will create implicit sequence "test_a_id_seq" for serial column "test_a.id"
  7. NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "pk_test_a_id" for table "test_a"
  8. CREATE TABLE
--方法
  1. create table test_b
  2. (
  3. id serial PRIMARY KEY,name character varying(128)
  4. );
  5.  
  6. NOTICE: CREATE TABLE will create implicit sequence "test_b_id_seq" for serial column "test_b.id"
  7. NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "test_b_pkey" for table "test_b"
  8. CREATE TABLE

--方法
  1. create table test_c
  2. (
  3. id integer PRIMARY KEY,name character varying(128)
  4. );
  5. NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "test_c_pkey" for table "test_c"
  6. CREATE TABLE
  7.  
  8.  
  9. CREATE SEQUENCE test_c_id_seq
  10. START WITH 1
  11. INCREMENT BY 1
  12. NO MINVALUE
  13. NO MAXVALUE
  14. CACHE 1;
  15. alter table test_c alter column id set default nextval('test_c_id_seq');

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

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

--比较三个表的表结构

  1. skytf=> \d test_a
  2. Table "skytf.test_a"
  3. Column | Type | Modifiers
  4. --------+------------------------+-----------------------------------------------------
  5. id | integer | not null default nextval('test_a_id_seq'::regclass)
  6. name | character varying(128) |
  7. Indexes:
  8. "pk_test_a_id" PRIMARY KEY,btree (id)
  9. skytf=> \d test_b
  10. Table "skytf.test_b"
  11. Column | Type | Modifiers
  12. --------+------------------------+-----------------------------------------------------
  13. id | integer | not null default nextval('test_b_id_seq'::regclass)
  14. name | character varying(128) |
  15. Indexes:
  16. "test_b_pkey" PRIMARY KEY,btree (id)
  17. skytf=> \d test_c
  18. Table "skytf.test_c"
  19. Column | Type | Modifiers
  20. --------+------------------------+-----------------------------------------------------
  21. id | integer | not null default nextval('test_c_id_seq'::regclass)
  22. name | character varying(128) |
  23. Indexes:
  24. "test_c_pkey" PRIMARY KEY,btree (id)

从上面可以看出,三个表表结构一模一样, 三种方法如果要寻找差别,可能仅有以下一点,
当 drop 表时,方法一和方法二会自动地将序列也 drop 掉,而方法三不会。


转贴:http://francs3.blog.163.com/blog/static/40576727201111715035318/

猜你在找的Postgre SQL相关文章