創(chuàng)建MySQL自動遞增字段的實際操作步驟
此文章主要向大家描述的是創(chuàng)建MySQL自動遞增字段的實際操作步驟,以及在其實際操作中值得我們大家注意的事項的描述,假如你對創(chuàng)建MySQL自動遞增字段的實際操作步驟有興趣了解的話,你就可以點擊以下的文章了。
創(chuàng)建MySQL自動遞增字段:
create table article //先創(chuàng)建一個表。
(
id int Prima(最完善的虛擬主機管理系統(tǒng))ry key auto_increment, //設置該字段為MySQL自動遞增字段。
title varchar(255)
);
insert into article values (null,'a'); //向數(shù)據(jù)庫中插入數(shù)據(jù)。
select * from article; 結果如下:
Id
Title
1
a
- insert into article values (null,’b’);
 - insert into article values (null,'c');
 - insert into article (title) values ('d');
 - select * from article;
 
結果如下:
Id
Title
1
a
2
b
3
c
4
d
但是Oracle(大型網(wǎng)站數(shù)據(jù)庫平臺)沒有這樣的功能,但是通過觸發(fā)器(trigger)和序列(sequence)可以實現(xiàn)。
假設關鍵字段為id,建一個序列,代碼為:
- create sequence seq_test_ids
 - minvalue 1
 - maxvalue 99999999
 - start with 1
 - increment by 1
 - nocache
 - order;
 - <!--[if !supportLineBreakNewLine]-->
 - <!--[endif]-->
 
建解發(fā)器代碼為:
- create or replace trigger tri_test_id
 - before insert on test_table
 - for each row
 - declare
 - nextid number;
 - begin
 - IF :new.id IS NULLor :new.id=0 THEN
 - select seq_test_id.nextval
 - into nextid
 - from sys.dual;
 - :new.id:=nextid;
 - end if;
 - end tri_test_id;
 
OK,上面的代碼就可以實現(xiàn)自動遞增的功能了。
以上的相關內(nèi)容就是對創(chuàng)建MySQL自動遞增字段的介紹,望你能有所收獲。
【編輯推薦】
- 實現(xiàn)MySQL數(shù)據(jù)庫同步大演練
 - 巧用c# 連接MySQL中文亂碼問題
 - 巧用MySQL加密函數(shù)對Web網(wǎng)站敏感數(shù)據(jù)進行保護
 - MySQL客戶端的軟件連接服務器演示
 - 把Access的數(shù)據(jù)導入MySQL數(shù)據(jù)庫的簡捷方案
 















 
 
 
 
 
 
 