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 掉, 而方法三不會。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM