在堆mysql数据库创建表时,如果我们把某个属性设置为auto_increment,也就是自动增长,我们在不要某行数数据时,当然是要删除该数据了,但是,有一个问题,摆在我们面前,数据时删除了,而新插入的数据的该属性值,不是在原来的基础上增加的,而是在删除的基础上增加的,这让人很不舒服,比如:
因为这张表已经创建了,我需要把这张显示出来:
mysql> show create table user1 \G;
//创建的表
Create Table: CREATE TABLE `user1` (
`uid` int(11) NOT NULL AUTO_INCREMENT,
`uname` char(20) NOT NULL,
`cid` int(11) DEFAULT '1',
PRIMARY KEY (`uid`),
KEY `idx_uname` (`uname`),
KEY `idx_cid` (`cid`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
//这是没删除的数据
mysql> select * from user1;
+-----+-------+------+
| uid | uname | cid |
+-----+-------+------+
| 1 | jack | 1 |
| 2 | mark | 1 |
| 3 | mary | 2 |
| 4 | rose | 5 |
+-----+-------+------+
4 rows in set (0.00 sec)
//删除uid为2和3的数据
mysql> delete from user1 where uid=2 or uid =3;
Query OK, 2 rows affected (0.00 sec)
//删除后的数据
mysql> select * from user1;
+-----+-------+------+
| uid | uname | cid |
+-----+-------+------+
| 1 | jack | 1 |
| 4 | rose | 5 |
+-----+-------+------+
2 rows in set (0.00 sec)
//我们通过批处理重新插入数据
mysql> insert into user1(uname,cid) values('alice',10),('alan',5),('jan',6);
Query OK, 3 rows affected (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 0
//重新查询数据
mysql> select * from user1;
+-----+-------+------+
| uid | uname | cid |
+-----+-------+------+
| 1 | jack | 1 |
| 4 | rose | 5 |
| 5 | alice | 10 |
| 6 | alan | 5 |
| 7 | jan | 6 |
+-----+-------+------+
5 rows in set (0.00 sec)
这个数据明显不是我们想要的数据,我们怎么办呢?
1、首先删除uid这个字段
2、在该表的第一列中新建该字段,会有神奇地事情出现
//我们删除这个uid这个字段(属性)
mysql> alter table user1 drop uid;
Query OK, 5 rows affected (0.09 sec)
Records: 5 Duplicates: 0 Warnings: 0
//重新查询
mysql> select * from user1;
+-------+------+
| uname | cid |
+-------+------+
| jack | 1 |
| rose | 5 |
| alice | 10 |
| alan | 5 |
| jan | 6 |
+-------+------+
5 rows in set (0.00 sec)
//再新建一个新的uid
mysql> alter table user1 add column uid int primary key auto_increment first;
Query OK, 0 rows affected (0.08 sec)
Records: 0 Duplicates: 0 Warnings: 0
//这是新建后的数据
mysql> select * from user1;
+-----+-------+------+
| uid | uname | cid |
+-----+-------+------+
| 1 | jack | 1 |
| 2 | rose | 5 |
| 3 | alice | 10 |
| 4 | alan | 5 |
| 5 | jan | 6 |
+-----+-------+------+
5 rows in set (0.00 sec)
* ps:我们决不能在插入数据的同时,采用这样删除再创建的方式,因为,这样会使数据造成混乱 *