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>

相关文章
相关标签/搜索