MySQL 序列使用

12 MySQL 序列使用

标签(空格分隔): MySQL


MySQL序列是一组整数:1, 2, 3, …,由于一张数据表只能有一个字段自增主键, 如果你想实现其他字段也实现自动增加,就可以使用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,
    -> date date not null,
    -> origin varchar(30) not null
    -> );
Query OK, 0 rows affected (0.04 sec)

mysql> insert into insect (id,name,date,origin)
    -> values
    -> (null,'housefly','2011-09-10','kitchen'),
    -> (null,'millipede','2001-09-10','driveway'),
    -> (null,'grasshopper','2001-09-10','front yard');
Query OK, 3 rows affected (0.01 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> select * from insect order by id;
+----+-------------+------------+------------+
| id | name        | date       | origin     |
+----+-------------+------------+------------+
|  1 | housefly    | 2011-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> select last_insert_id();
+------------------+
| last_insert_id() |
+------------------+
|                1 |
+------------------+

重置序列

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

mysql> alter table insect drop id;
Query OK, 3 rows affected (0.32 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> alter table insect
    -> add id int unsigned not null auto_increment first,
    -> add primary key(id);
Query OK, 0 rows affected (0.12 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> select * from insect;
+----+-------------+------------+------------+
| id | name        | date       | origin     |
+----+-------------+------------+------------+
|  1 | housefly    | 2011-09-10 | kitchen    |
|  2 | millipede   | 2001-09-10 | driveway   |
|  3 | grasshopper | 2001-09-10 | front yard |
+----+-------------+------------+------------+
3 rows in set (0.00 sec)

设置序列的开始值

一般情况下序列的开始值为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;

猜你喜欢

转载自blog.csdn.net/weixin_42061048/article/details/80594867