Application scenarios
In the daily development of our software, there are often unique constraints that require a certain field value, such as: mobile phone number, email address...
sql operation
1. Create a user table
create table user(
id varchar(255) comment '主键id',
name varchar(255) comment '用户名',
phone varchar(11) comment '手机号',
email varchar(64) comment '邮箱地址',
primary key(id)
) comment '用户表';
2. Insert two pieces of data
INSERT INTO `test_db`.`user` (`id`, `name`, `phone`, `email`) VALUES ('2871c6db-2e4f-11e8-9242-00163e06348c', 'Kevin', '18233339999', '[email protected]');
INSERT INTO `test_db`.`user` (`id`, `name`, `phone`, `email`) VALUES ('42895546-2e4f-11e8-9242-00163e06348c', 'Nana', '18233339999', '[email protected]');
3. Observe two data (the mobile phone number is the same, the requirement is that the mobile phone number is not allowed to be the same)
4. Modify to add a unique constraint to the phone field
alter table user add unique(phone); -- 注意执行这步前需要把重复的字段值删除或者备份一下数据
5. After adding a unique constraint, inserting a duplicate value into the phone field will result in an error