龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 数据库类 > MySQL 技术 >

创建MySQL自动递增字段的实际操作步骤

时间:2011-04-12 23:18来源:未知 作者:admin 点击:
分享到:
此文章主要向大家描述的是创建 MySQL 自动递增字段的实际操作步骤,以及在其实际操作中值得我们大家注意的事项的描述,假如你对创建MySQL自动递增字段的实际操作步骤有兴趣了解的

此文章主要向大家描述的是创建MySQL自动递增字段的实际操作步骤,以及在其实际操作中值得我们大家注意的事项的描述,假如你对创建MySQL自动递增字段的实际操作步骤有兴趣了解的话,你就可以点击以下的文章了。

创建MySQL自动递增字段:

create table article //先创建一个表。

(

id int Prima(最完善的虚拟主机管理系统)ry key auto_increment, //设置该字段为MySQL自动递增字段。

title varchar(255)

);

insert into article values (null,'a'); //向数据库中插入数据。

select * from article; 结果如下:

Id

Title

1

a

  1. insert into article values (null,’b’);  
  2. insert into article values (null,'c');  
  3. insert into article (title) values ('d');  
  4. select * from article;   

结果如下:

Id

Title

1

a

2

b

3

c

4

d

但是Oracle(大型网站数据库平台)没有这样的功能,但是通过触发器(trigger)和序列(sequence)可以实现。

假设关键字段为id,建一个序列,代码为:

  1. create sequence seq_test_ids  
  2. minvalue 1  
  3. maxvalue 99999999  
  4. start with 1  
  5. increment by 1  
  6. nocache  
  7. order;  
  8. <!--[if !supportLineBreakNewLine]--> 
  9. <!--[endif]--> 

建解发器代码为:

  1. create or replace trigger tri_test_id  
  2. before insert on test_table   
  3. for each row  
  4. declare  
  5. nextid number;  
  6. begin  
  7. IF :new.id IS NULLor :new.id=0 THEN  
  8. select seq_test_id.nextval  
  9. into nextid  
  10. from sys.dual;  
  11. :new.id:=nextid;  
  12. end if;  
  13. end tri_test_id; 

OK,上面的代码就可以实现自动递增的功能了。

以上的相关内容就是对创建MySQL自动递增字段的介绍,望你能有所收获。


精彩图集

赞助商链接