一。把主鍵定義為自動成長標識符類型
在mysql中,如果把表的主鍵設為auto_increment類型,資料庫就會自動為主鍵賦值。例如:
create table customers(id int auto_increment primary key not null, name varchar(15));
insert into customers(name) values("name1"),("name2");
select id from customers;
以上sql語句先建立了customers表,然後插入兩條記錄,在插入時僅僅設定了name欄位的值。最後查詢表中id欄位,查詢結果為:
id
1
2
由此可見,一旦把id設為auto_increment類型,mysql資料庫會自動按遞增的方式為主鍵賦值。
------------------------
二。在MS SQLServer中,如果把表的主鍵設為identity類型,資料庫就會自動為主鍵賦值。例如:
create table customers(id int identity(1,1) primary key not null, name varchar(15));
insert into customers(name) values("name1"),("name2");
select id from customers;
查詢結果和mysql的一樣。由此可見,一旦把id設為identity類型,MS SQLServer資料庫會自動按遞增的方式為主鍵賦值。identity包含兩個參數,第一個參數表示起始值,第二個參數表示增量。
2、從序列中擷取自動成長的標識符、
------------------------
三。在Oracle中,可以為每張表的主鍵建立一個單獨的序列,然後從這個序列中擷取自動增加的標識符,把它賦值給主鍵。例如一下語句建立了一個名為customer_id_seq的序列,這個序列的起始值為1,增量為2。
create sequence customer_id_seq increment by 2 start with 1
一旦定義了customer_id_seq序列,就可以訪問序列的curval和nextval屬性。
curval:返回序列的當前值
nextval:先增加序列的值,然後返回序列值
以下sql語句先建立了customers表,然後插入兩條記錄,在插入時設定了id和name欄位的值,其中id欄位的值來自於customer_id_seq序列。最後查詢customers表中的id欄位。
create table customers(id int primary key not null, name varchar(15));
insert into customers values(customer_id_seq.curval, "name1"),(customer_id_seq.nextval, "name2");
select id from customers;
如果在oracle中執行以上語句,查詢結果為:
id
1
3
------------------------
四。sqlite 將欄位設定為自動曾長型
簡短回答:聲明為 INTEGER PRIMARY KEY 的列將會自動成長。