当前位置: 移动技术网 > IT编程>数据库>Mysql > MySQL 序列 AUTO_INCREMENT详解及实例代码

MySQL 序列 AUTO_INCREMENT详解及实例代码

2017年12月12日  | 移动技术网IT编程  | 我要评论

mysql 序列 auto_increment详解及实例代码

mysql序列是一组整数:1, 2, 3, ...,由于一张数据表只能有一个字段自增主键, 如果你想实现其他字段也实现自动增加,就可以使用mysql序列来实现。

本章我们将介绍如何使用mysql的序列。

使用auto_increment

mysql中最简单使用序列的方法就是使用 mysql auto_increment 来定义列。

实例

以下实例中创建了数据表insect, insect中id无需指定值可实现自动增长。

mysql> create table insect
  -> (
  -> id int unsigned not null auto_increment,
  -> primary key (id),
  -> name varchar(30) not null, # type of insect
  -> date date not null, # date collected
  -> origin varchar(30) not null # where collected
);
query ok, 0 rows affected (0.02 sec)
mysql> insert into insect (id,name,date,origin) values
  -> (null,'housefly','2001-09-10','kitchen'),
  -> (null,'millipede','2001-09-10','driveway'),
  -> (null,'grasshopper','2001-09-10','front yard');
query ok, 3 rows affected (0.02 sec)
records: 3 duplicates: 0 warnings: 0
mysql> select * from insect order by id;
+----+-------------+------------+------------+
| id | name    | date    | origin   |
+----+-------------+------------+------------+
| 1 | housefly  | 2001-09-10 | kitchen  |
| 2 | millipede  | 2001-09-10 | driveway  |
| 3 | grasshopper | 2001-09-10 | front yard |
+----+-------------+------------+------------+
3 rows in set (0.00 sec)

 获取auto_increment值

在mysql的客户端中你可以使用 sql中的last_insert_id( ) 函数来获取最后的插入表中的自增列的值。

在php或perl脚本中也提供了相应的函数来获取最后的插入表中的自增列的值。

perl实例

使用 mysql_insertid 属性来获取 auto_increment 的值。 实例如下:

$dbh->do ("insert into insect (name,date,origin)
values('moth','2001-09-14','windowsill')");
my $seq = $dbh->{mysql_insertid};

php实例

php 通过 mysql_insert_id ()函数来获取执行的插入sql语句中 auto_increment列的值。

mysql_query ("insert into insect (name,date,origin)
values('moth','2001-09-14','windowsill')", $conn_id);
$seq = mysql_insert_id ($conn_id);

 重置序列

如果你删除了数据表中的多条记录,并希望对剩下数据的auto_increment列进行重新排列,那么你可以通过删除自增的列,然后重新添加来实现。 不过该操作要非常小心,如果在删除的同时又有新记录添加,有可能会出现数据混乱。操作如下所示:

mysql> alter table insect drop id;
mysql> alter table insect
  -> add id int unsigned not null auto_increment first,
  -> add primary key (id);

 设置序列的开始值

一般情况下序列的开始值为1,但如果你需要指定一个开始值100,那我们可以通过以下语句来实现:

mysql> create table insect
  -> (
  -> id int unsigned not null auto_increment = 100,
  -> primary key (id),
  -> name varchar(30) not null, # type of insect
  -> date date not null, # date collected
  -> origin varchar(30) not null # where collected
);

或者你也可以在表创建成功后,通过以下语句来实现:

mysql> alter table t auto_increment = 100;

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网