注意Mysql数据截断

Beware of MySQL Data Truncation
http://www.mysqlperformanceblog.com/2009/02/07/beware-of-mysql-data-truncation/

 

比如:有一个表aritcle和另一个表article_comment,关联是article的id

CREATE TABLE `article` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(200) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;

 

CREATE TABLE `article_comment` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `text` varchar(200) NOT NULL,
  `article_id` int(10) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  KEY `art_id` (`article_id`),
  CONSTRAINT `art_id` FOREIGN KEY (`article_id`) REFERENCES `article` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB;

 

set sql_mode='';

insert into article values(12345678901,'name1');

insert into article_comment(text,article_id) values('text1',12345678901);

insert into article_comment(text,article_id) values('text2',12345678902);

查看数据:

article表

4294967295 name1
article_comment表

1 text1 4294967295
2 text2 4294967295
从中可以看出,本来第二个插入的评论想关联另一个文章,但是却关联到了第一篇文章,这是因为Mysql的Data Truncation

show warnings显示

Warning | 1265 | Data truncated for column 'article_id' at row 1

这会造成:

(1)评论关联到错误的文章

(2)同一篇文章关联到许多的评论(这会造成性能问题)

 

怎样解决呢?

set sql_mode='STRICT_ALL_TABLES';

insert into article_comment(text,article_id) values('text1',12345678903);

这会报错:

[SQL] insert into article_comment(text,article_id) values('text1',12345678903);
[Err] 1264 - Out of range value for column 'article_id' at row 1

因此也就避免了上述问题。

 

你可能感兴趣的:(sql,mysql,null,table,insert,Warnings)