[关闭]
@yanglt7 2018-06-06T06:47:30.000000Z 字数 1989 阅读 714

12 MySQL 序列使用

MySQL


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

使用AUTO_INCREMENT

实例

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

  1. mysql> create table insect
  2. -> (
  3. -> id int unsigned not null auto_increment,
  4. -> primary key (id),
  5. -> name varchar(30) not null,
  6. -> date date not null,
  7. -> origin varchar(30) not null
  8. -> );
  9. Query OK, 0 rows affected (0.04 sec)
  10. mysql> insert into insect (id,name,date,origin)
  11. -> values
  12. -> (null,'housefly','2011-09-10','kitchen'),
  13. -> (null,'millipede','2001-09-10','driveway'),
  14. -> (null,'grasshopper','2001-09-10','front yard');
  15. Query OK, 3 rows affected (0.01 sec)
  16. Records: 3 Duplicates: 0 Warnings: 0
  17. mysql> select * from insect order by id;
  18. +----+-------------+------------+------------+
  19. | id | name | date | origin |
  20. +----+-------------+------------+------------+
  21. | 1 | housefly | 2011-09-10 | kitchen |
  22. | 2 | millipede | 2001-09-10 | driveway |
  23. | 3 | grasshopper | 2001-09-10 | front yard |
  24. +----+-------------+------------+------------+
  25. 3 rows in set (0.00 sec)

获取AUTO_INCREMENT值

  1. mysql> select last_insert_id();
  2. +------------------+
  3. | last_insert_id() |
  4. +------------------+
  5. | 1 |
  6. +------------------+

重置序列

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

  1. mysql> alter table insect drop id;
  2. Query OK, 3 rows affected (0.32 sec)
  3. Records: 3 Duplicates: 0 Warnings: 0
  4. mysql> alter table insect
  5. -> add id int unsigned not null auto_increment first,
  6. -> add primary key(id);
  7. Query OK, 0 rows affected (0.12 sec)
  8. Records: 0 Duplicates: 0 Warnings: 0
  9. mysql> select * from insect;
  10. +----+-------------+------------+------------+
  11. | id | name | date | origin |
  12. +----+-------------+------------+------------+
  13. | 1 | housefly | 2011-09-10 | kitchen |
  14. | 2 | millipede | 2001-09-10 | driveway |
  15. | 3 | grasshopper | 2001-09-10 | front yard |
  16. +----+-------------+------------+------------+
  17. 3 rows in set (0.00 sec)

设置序列的开始值

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

  1. mysql> create table insect
  2. -> (
  3. -> id int unsigned not null auto_increment,
  4. -> primary key(id),
  5. -> name varchar(30) not null,
  6. -> date date not null,
  7. -> origin varchar(30) not null
  8. -> )engine=innodb auto_increment=100 charset=utf8;

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

  1. mysql> ALTER TABLE t AUTO_INCREMENT = 100;
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注