animals,包含 id,name,foot 三個欄位,其中 id 定義為 auto_increment 的主鍵,讓該列數字編號不重複,且每筆紀錄新增時自動加 1。
[root@kvm8 ~]# mysql -s -uroot -p123qwe
mysql> use dyw;
mysql> create table animals(
-> id int unsigned not null auto_increment,
-> primary key(id),
-> name varchar(20) not null,
-> foot tinyint unsigned not null
-> );
mysql>
animals 新增三筆資料,其中 id 故意設定為空值。
mysql> insert into animals(id,name,foot)
-> values
-> (NULL,'dog',4),
-> (NULL,'cat',4),
-> (NULL,'bird',2);
mysql>
animals,欄位 id 並沒有因用戶設定為空值而真的為空值,而是從 1 開始編號,每筆自動增加 1。
mysql> select * from animals; id name foot 1 dog 4 2 cat 4 3 bird 2 mysql>
id=3 的紀錄。
mysql> delete from animals where id=3; mysql>
mysql> insert into animals(name,foot) values ('chicken',2);
mysql>
animals 中 chicken 紀錄的 id=4,並不是 3。
mysql> select * from animals; id name foot 1 dog 4 2 cat 4 4 chicken 2 mysql>
id=3 的紀錄,新增的紀錄 id=4,造成 id 不連續,如果要重新編號,必須先刪除 id 欄位,再重新產生,其編號就會重新編號。不過要特別注意的是,若此資料表與其他資料表關聯,可能會造成資料對應錯誤,要特別小心。刪除欄位 id。
mysql> alter table animals drop id; mysql>
id 欄位於資料表 animals 最前頭 (first 就是指定在第一列) 。
mysql> alter table animals
-> add id int unsigned not null auto_increment first,
-> add primary key (id);
mysql>
animals,id 編號已從 1 重新編號。
mysql> select * from animals; id name foot 1 dog 4 2 cat 4 3 chicken 2 mysql>
mysql> ALTER TABLE animals AUTO_INCREMENT = 15; Query OK, 3 rows affected (3.31 sec) Records: 3 Duplicates: 0 Warnings: 0
mysql> insert into animals(name,foot) values ('bird',2);
Query OK, 1 row affected (0.47 sec)
animals,新增的紀錄 id 編號已從 15 開始。
mysql> select * from animals; +----+---------+------+ | id | name | foot | +----+---------+------+ | 1 | dog | 4 | | 2 | cat | 4 | | 3 | chicken | 2 | | 15 | bird | 2 | +----+---------+------+ 4 rows in set (0.00 sec)