Chinaunix首页 | 论坛 | 博客
  • 博客访问: 443122
  • 博文数量: 97
  • 博客积分: 1552
  • 博客等级: 上尉
  • 技术积分: 1091
  • 用 户 组: 普通用户
  • 注册时间: 2012-05-17 17:05
个人简介

专注于大规模运维场景运维工具解决方案。欢迎有这方面兴趣的朋友跟我联系。

文章分类

全部博文(97)

文章存档

2014年(12)

2013年(25)

2012年(60)

我的朋友

分类: 数据库开发技术

2012-08-01 20:50:49

表结构如下

点击(此处)折叠或打开

  1. +-------+-----------------------------------------------
  2. ---------------------------+
  3. | Table | Create Table
  4.                            |
  5. +-------+-----------------------------------------------
  6. ---------------------------+
  7. | abc | CREATE TABLE `abc` (
  8.   `id` int(11) NOT NULL auto_increment,
  9.   `a` char(255) default NULL,
  10.   PRIMARY KEY (`id`)
  11. ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 |
  12. +
执行如下的一条SQL语句:
insert into abc(`id`,`a`) values(0,'a');
查看结果:
mysql> select * from abc;
+----+------+
| id | a    |
+----+------+
|  1 | a    |
+----+------+
发现这个id变成了1. 为什么?是什么原因引起的?
GOOGLE开始....
网友1:说可以这样写SQL语句
insert into abc set id = 0,a = 'a';得到id = 0。
在本机环境跑了一下运行发现没用!
网友2:可以这样来操作
mysql> set sql_mode='NO_AUTO_VALUE_ON_ZERO';
这样就可以做到让0插入进去了。
实验发现可以的[可行 ]
NO_AUTO_VALUE_ON_ZERO影响AUTO_INCREMENT列的处理。一般情况,你可以向该列插入NULL或0生成下一个序列号。NO_AUTO_VALUE_ON_ZERO禁用0,因此只有NULL可以生成下一个序列号。
如果将0保存到表的AUTO_INCREMENT列,该模式会很有用。(不推荐采用该惯例)。
网友3:如果mysqldump的出来的SQL再导入到新库发现没有0了。
如果你用mysqldump转储表并重载,MySQL遇到0值一般会生成新的序列号,生成的表的内容与转储的表不同。重载转储文件前启用NO_AUTO_VALUE_ON_ZERO可以解决该问题。
解决办法就是:要在load这个SQL之前加上这句命令即可

既然上面提到这个sql_mode关键字那可以详细来聊聊这个
查看当前的变量值:
mysql>SELECT @@SESSION.sql_mode;
这个是跟终端有关,类似于set names utf8操作。如果没有进行个性设置的话那默认会继承于global 类型的

官方:

 NO_AUTO_VALUE_ON_ZERO

NO_AUTO_VALUE_ON_ZERO affects handling of AUTO_INCREMENT columns. Normally, you generate the next sequence number for the column by inserting either NULL or 0 into it. NO_AUTO_VALUE_ON_ZERO suppresses this behavior for 0 so that only NULL generates the next sequence number.

This mode can be useful if 0 has been stored in a table's AUTO_INCREMENT column. (Storing 0 is not a recommended practice, by the way.) For example, if you dump the table with mysqldump and then reload it, MySQL normally generates new sequence numbers when it encounters the 0 values, resulting in a table with contents different from the one that was dumped. Enabling NO_AUTO_VALUE_ON_ZERO before reloading the dump file solves this problem. mysqldump now automatically includes in its output a statement that enablesNO_AUTO_VALUE_ON_ZERO, to avoid this problem.

总结:

1、解决办法就是加上这个set语句跟set names utf8的行为一样

阅读(1927) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~