日期:2014-05-16  浏览次数:20511 次

自增字段 auto_commit的研究分析

MySQL自增字段,自增字段计数器在主存储里面,不在硬盘上(This counter is stored only in main memory, not on disk)。
1,添加表,设立自增主键字段
create table t(id int primary key auto_increment, name varchar(3000)) engine=innodb;


2,可以让系统自增,也可以自己手动设置输入自增。
insert into t select 4, 'a44';
insert into t(name) select 'a8';


3,查询当前表的自增值
SELECT MAX(id) FROM t FOR UPDATE;


4,如果你设置的自增值超过当前最大自增值,则以你设置的自增值为准,开始自增。例如:
SELECT MAX(id) FROM t FOR UPDATE;得出值为4,然后你insert into t select 9, 'a44';那么这个时候,MAX(id)就是9,
那么下一个自增值就是16而不是5,当然了,你执行语句insert into t select 5, 'a44';也是可以通过的。


5,如果有事务的话,insert之后了rollback,autocommit里面的counter不会回滚,依然+1.


6,参数
innodb_autoinc_lock_made


在my.cnf里面直接添加一行
[mysqld]
innodb_autoinc_lock_mode = 0
然后重启mysql数据库,执行show variables like '%innodb_autoinc_lock_mode%'; 发现值为0,修改成功。


7,一个只有自增字段的表的录入方法
CREATE TABLE `t1` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


7.1 自己设值insert进去
insert into t1 select 1;
mysql> select * from t1;
+----+
| id |
+----+
|  1 |
+----+
1 row in set (0.00 sec)


7.2 调用mysql的函数 LAST_INSERT_ID();

mysql> SELECT LAST_INSERT_ID();
+------------------+
| LAST_INSERT_ID() |
+------------------+
|                0 |
+------------------+
1 row in set (0.01 sec) 
ps:这里是0,是因为上一次insert是录入的值,没有调用此函数,所以从0时初始值,但是不影响正常的insert到表的值。


mysql> insert into t1 select LAST_INSERT_ID();
Query OK, 1 row affected (0.00 sec)
Records: 1  Duplicates: 0  Warnings: 0

mysql> select * from t1;
+----+
| id |
+----+
|  1 |
|  2 |
+----+
2 rows in set (0.00 sec)

mysql>