扫码一下
查看教程更方便
mysql 序列是一组整数:1, 2, 3, ...,由于一张数据表只能有一个字段自增主键, 如果你想实现其他字段也实现自动增加,就可以使用mysql序列来实现。
本章我们将介绍如何使用mysql的序列。
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)
在mysql的客户端中你可以使用 sql中的last_insert_id( ) 函数来获取最后的插入表中的自增列的值。
在php或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 通过 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,
-> primary key (id),
-> name varchar(30) not null,
-> date date not null,
-> origin varchar(30) not null
)engine=innodb auto_increment=100 charset=utf8;
或者你也可以在表创建成功后,通过以下语句来实现:
mysql> alter table t auto_increment = 100;