mysql唯一约束特点是不能重复允许为null
参考网址:
https://mp.weixin.qq.com/s/hmro3mAmEWDgpanH3DsPpQ
测试建表脚本
建表脚本
-- 唯一索引(不设置not null)
create table demo1(
id int unsigned primary key auto_increment,
phone_no char(11) ,
unique key uk_phone_no (`phone_no`) using btree
);
-- 复合唯一索引
CREATE TABLE `demo` (
`id` int(10) unsigned NOT NULL,
`delete_at` int(10) unsigned DEFAULT NULL,
`rname` varchar(30) DEFAULT NULL,
`rage` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_delete_at_rname_rage` (`rname`,`rage`,`delete_at`)
)
插入测试数据脚本
-- 向demo1表中插入测试数据
insert into demo1 values (null , null);
insert into demo1 values (null , null);
insert into demo1 values (null , null);
-- 向demo表中插入测试数据
insert into demo values ( 1 , 100 , 'aaaa' , 200);
insert into demo values ( 2 , null , 'aaaa' , 200);
insert into demo values ( 3 , null , 'aaaa' , 200);
出现问题
- demo1表中设置唯一索引的列可以插入多个null值
- demo表中复合唯一索引有一列设为null值,那么会出现nul值可以重复的情况
结论
1.建表如果没有特殊含义,尽量列都是not null,避免一些没有必要的麻烦
详情参考:
https://mp.weixin.qq.com/s?__biz=Mzg5MDEzMjEwNw==&mid=2247488231&idx=2&sn=b381d920c6ca0bf82c951efd85044288&chksm=cfe01103f8979815832cb59330f1b8ea3e596281fbceb60eb8be3348e059b2f4a44cefe2793f&mpshare=1&scene=23&srcid=0121fK6CIwDKE3y3kVYyMmsT&sharer_sharetime=1611193613520&sharer_shareid=9d1e76e919cc0b2f3ca23ed1f5ef67a8#rd
下面是某互联网公司对mysql建表规范,建议列约束都是not null
2.唯一约束特点是不能重复!!(允许为空)
个人csdn博客网址:https://blog.csdn.net/shaoming314
![jam](https://i-blog.csdnimg.cn/blog_migrate/902f9ea4e6285ceba0d18af8e9857bb2.jpeg)
个人博客网址:www.shaoming.club
![halo](https://gitee.com/shao_ming314/picture/raw/master/image/halo.jpg)
个人gitee地址:https://gitee.com/shao_ming314/note
![111](https://gitee.com/shao_ming314/picture/raw/master/image/111.jpg)
勇敢牛牛,不怕困难
_ming314/picture/raw/master/image/111.jpg" alt=“111” style=“zoom:33%;” />
勇敢牛牛,不怕困难
![img](https://i-blog.csdnimg.cn/blog_migrate/54e9eca74795660a3cac4b42388b9e4d.jpeg)