mysql自增id列
如果希望在每次插入新记录时,自动地创建主键字段的值。可以在表中创建一个 auto-increment 字段。MySQL 使用 AUTO_INCREMENT 关键字来执行 auto-increment 任务。默认地AUTO_INCREMENT 的开始值是 1,每条新记录递增 1。
主键又称主关键字,主关键字(primary key)是表中的一个或多个字段,它的值用于唯一地标识表中的某一条记录。
测试创建一个test表:
mysql> create table test (
aid int not null auto_increment,
site_id int, cout int, date date,
primary key (aid) );
Query OK, 0 rows affected (0.01 sec)
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)
mysql>
尝试插入两条数据
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>