問題說明:
今天從oracle遷移數據到mysql碰到個需求:原先的主鍵字段需要改成mysql中的自增字段,而且原先數據的值不能變,以後新插入的值從原先數據最大的值開始自增。
解決辦法:
構建環境:
mysql> CREATE TABLE test
-> (
-> id INT UNSIGNED NOT NULL PRIMARY KEY,
-> username VARCHAR(15) NOT NULL
-> );
Query OK, 0 rows affected (0.00 sec)
mysql> insert into test values(5,'test1');
Query OK, 1 row affected (0.00 sec)
mysql> insert into test values(8,'test2');
Query OK, 1 row affected (0.00 sec)
mysql> insert into test values(4,'test3');
Query OK, 1 row affected (0.00 sec)
mysql> insert into test values(100,'test4');
Query OK, 1 row affected (0.00 sec)
將主鍵改成自增字段:
mysql> alter table test change id id int AUTO_INCREMENT;
Query OK, 4 rows affected (0.01 sec)
Records: 4 Duplicates: 0 Warnings: 0
插入新數據:
mysql> insert into test(username) values('test6');
Query OK, 1 row affected (0.00 sec)
查看:
發現沒問題,直接修改字段爲自增序列就可以完成。
mysql> select * from test;
+-----+----------+
| id | username |
+-----+----------+
| 4 | test3 |
| 5 | test1 |
| 8 | test2 |
| 100 | test4 |
| 101 | test6 |
+-----+----------+
5 rows in set (0.00 sec)
問題延伸:
1、MySQL創建表以後,auto_increment的字段自增值是從1開始的,寫入0會被當做null值處理從而寫入當前最大值的下一個值(即表定義中auto_increment的值),如果要從0開始如何操作呢?
解決辦法:
SET sql_mode='NO_AUTO_VALUE_ON_ZERO';
2、如何指定自增字段從哪個值開始增長,增長步長?
解決辦法:
- auto_increment_offset:表示自增長字段從那個數開始,他的取值範圍是1 … 65535
- auto_increment_increment:表示自增長字段每次遞增的量,其默認值是1,取值範圍是1 … 65535