Mysql 数据类型之 AUTO_INCREMENT 使用(二)

        AUTO_INCREMENT介绍,在oracle数据库中如果想让某列数值自动增加1的话,还需要配合trigger与sequences,可在mysql中这个auto_increment就可以直接完成这样的任务,auto_increment值从1开始,每行增加1,如果插入NULL值到该列时,此时会插入一个比该列中当前最大值加1的值 ,在一张表中只能有一列auto_increment,所以想要使用auto_increment列时,应该定义该列为NOT NULL,并定义为primary key或unique键,下面用例子来说明如何使用:

例:
(1)建立测试表ai1
mysql> create table ai1 (id int auto_increment not null primary key,name char(10));
Query OK, 0 rows affected (0.02 sec)

(2)插入一条空数据
mysql> insert into ai1 values ();
Query OK, 1 row affected (0.00 sec)

mysql> select * from ai1;
+----+------+
| id | name |
+----+------+
1 | NULL |
+----+------+
1 row in set (0.00 sec)

(3)插入一条跳跃id的新数据
mysql> insert into ai1 values (4,'suzzy');
Query OK, 1 row affected (0.00 sec)

mysql> select * from ai1;
+----+-------+
| id | name  |
+----+-------+
|  1 | NULL  |
|  2 | sam   |
4 | suzzy |
+----+-------+
3 rows in set (0.00 sec)

(4)插入一条id为空的数据,此时查看id的变化,会按照我们之前定义的,用最大值加1
mysql> insert into ai1 values (null,'suzzy');
Query OK, 1 row affected (0.00 sec)

mysql> select * from ai1;
+----+-------+
| id | name  |
+----+-------+
|  1 | NULL  |
|  2 | sam   |
|  4 | suzzy |
5 | suzzy |
+----+-------+
4 rows in set (0.00 sec)

注:如果在一张表中加两列auto_increment列时,会报错:
mysql> create table ai1 (id int auto_increment not null primary key,id2 int auto_increment not null);
ERROR 1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a key

总结:
          auto_increment属性,大大的解决了很多生产环境当中,序列的问题,看似简单的小属性参数,却能看出来设计者的高明。真是越来越喜欢MYSQL,有好多小东西值得我们学习。
Where there’s a will , there ’s a way.

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/26148431/viewspace-1966613/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/26148431/viewspace-1966613/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值