MySQL inserts duplicate records despite unique index | Lease_MySQL

WBOY
发布: 2016-05-31 08:47:05
原创
1104 人浏览过

Okay, so I thought I knew quite a bit about databases and so I added a unique index. For those who do not know:

A UNIQUE index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. – MySQL manual

I added the unique index to my table that made it look like this:

CREATE TABLE `table` (`a` int(11) DEFAULT NULL,`b` int(11) DEFAULT NULL,`c` int(11) DEFAULT NULL,UNIQUE KEY `a_b_c` (`a`,`b`,`c`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
登录后复制

I was trying to insert or increment values in it like this:

INSERT INTO `table` (a,b,c) VALUES (1,NULL,3),(1,NULL,3) ON DUPLICATE KEY UPDATE c=c+VALUES(c);
登录后复制

I expected to get the following result:

mysql> select * from `table`;+------+------+------+| a| b| c|+------+------+------+|1 | NULL |6 |+------+------+------+1 row in set (0.00 sec)
登录后复制

But it did not do that! I got this result instead:

mysql> select * from `table`;+------+------+------+| a| b| c|+------+------+------+|1 | NULL |3 ||1 | NULL |3 |+------+------+------+2 rows in set (0.00 sec)
登录后复制

I was clueless until I read the documentation of MySQL a little better:

This constraint does not apply to NULL values except for the BDB storage engine. For other engines, a UNIQUE index permits multiple NULL values for columns that can contain NULL. – MySQL manual

Especially the part where it says: “does not apply to NULL values” makes things much, much clearer. :-) Note that Microsoft SQL Server behaves different (they way I expected). So keep this is mind when using a unique index in MySQL, because I certainly did not expect this behavior!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!