@yanglt7
2018-06-06T06:47:30.000000Z
字数 1989
阅读 714
MySQL
MySQL序列是一组整数:1, 2, 3, ...,由于一张数据表只能有一个字段自增主键, 如果你想实现其他字段也实现自动增加,就可以使用MySQL序列来实现。
以下实例中创建了数据表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)
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;