mysql自增id列

若是但願在每次插入新記錄時,自動地建立主鍵字段的值。能夠在表中建立一個 auto-increment 字段。MySQL 使用 AUTO_INCREMENT 關鍵字來執行 auto-increment 任務。默認地AUTO_INCREMENT 的開始值是 1,每條新記錄遞增 1。mysql

主鍵又稱主關鍵字,主關鍵字(primary key)是表中的一個或多個字段,它的值用於惟一地標識表中的某一條記錄。sql

測試建立一個test表:測試

mysql> create table test (rem

             aid int not null auto_increment,it

             site_id int, cout int, date date,table

             primary key (aid) );test

Query OK, 0 rows affected (0.01 sec)date

mysql> desc test;
+---------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+---------+------+-----+---------+----------------+
| aid | int(11) | NO | PRI | NULL | auto_increment |
| site_id | int(11) | YES | | NULL | |
| cout | int(11) | YES | | NULL | |
| date | date | YES | | NULL | |
+---------+---------+------+-----+---------+----------------+
4 rows in set (0.00 sec)select

mysql> im

嘗試插入兩條數據

mysql> insert into test9 (site_id , cout, date) value  ( 1,45,'2019-10-10' ),( 1,45,'2016-05-10' );
Query OK, 2 row affected (0.00 sec)

mysql> select * from test9;
+-----+---------+------+------------+
| aid | site_id | cout | date |
+-----+---------+------+------------+
| 2 | 1 | 45 | 2019-10-10 |
| 4 | 1 | 45 | 2016-05-10 |
+-----+---------+------+------------+
2 rows in set (0.00 sec)

mysql>

發現aid是有自動添加並且遞增,但遞增都是加2.

應該是mysql環境設置問題,auto_increment的默認值是2,更改成1 就行

mysql> set @@global.auto_increment_increment = 1;
Query OK, 0 rows affected (0.01 sec)

mysql> set @@auto_increment_increment =1;
Query OK, 0 rows affected (0.00 sec)

再嘗試添加數據,就能夠了

mysql> insert into test9 (site_id , cout, date) value ( 3,55,'2017-05-20' ),( 4,45,'2017-08-20' );
Query OK, 2 row affected (0.00 sec)

mysql> select * from test9;
+-----+---------+------+------------+
| aid | site_id | cout | date |
+-----+---------+------+------------+
| 2 | 1 | 45 | 2019-10-10 |
| 4 | 1 | 45 | 2016-05-10 |
| 5 | 3 | 55 | 2017-05-20 |
| 6 | 4 | 45 | 2017-08-20 |
+-----+---------+------+------------+
4rows in set (0.00 sec)

mysql>

相關文章
相關標籤/搜索