6人参与 • 2026-02-01 • Mysql
唯一索引是mysql中保证数据完整性的重要工具,它强制要求索引列的值必须唯一(允许null值,但多null值会被视为不同值)。与主键索引不同,唯一索引允许存在多个,且不隐含非空约束。典型应用场景包括:
语法模板
create table table_name (
column1 datatype unique, -- 单列唯一索引
column2 datatype,
...,
unique (col_a, col_b) -- 多列组合唯一索引
);
实战示例
create table users (
id int auto_increment primary key,
username varchar(50) not null unique, -- 单列唯一索引
email varchar(100) not null,
phone varchar(20),
index idx_email_phone (email, phone) unique -- 组合唯一索引
);
效果验证
插入重复用户名或(email+phone)组合时,mysql将抛出error 1062 (23000): duplicate entry错误。
方法1:alter table(推荐)
alter table products add unique uk_product_sku (sku); -- 单列索引 alter table orders add unique uk_order_user_time (user_id, order_time); -- 组合索引
方法2:create index
create unique index idx_unique_username on customers(username);
1. 索引命名规范
建议使用前缀uk_(unique key)或uniq_开头,如uk_user_email,便于维护。
2. 处理冲突数据
添加唯一索引前,需先清理重复数据:
-- 查找重复数据 select col, count(*) from table_name group by col having count(*) > 1; -- 删除重复记录(保留最新) delete t1 from table_name t1 inner join table_name t2 where t1.id > t2.id and t1.col = t2.col;
3. 性能影响评估
4. 特殊场景处理
insert ignoreinsert ignore into users (username) values ('john');
create table logs (
id int,
event_date date,
unique (id, event_date) -- 仅当event_date在最近30天时生效
) partition by range columns(event_date);
alter table articles add unique (title(50)); -- 仅索引前50字符
optimize table重建索引完整示例sql
-- 创建商品表并添加唯一索引
create table products (
id int auto_increment primary key,
sku varchar(20) not null,
name varchar(100) not null,
price decimal(10,2) not null,
created_at timestamp default current_timestamp,
constraint uk_product_sku unique (sku) -- 命名约束
) engine=innodb default charset=utf8mb4;
-- 添加组合唯一索引(订单号+用户id)
alter table orders add unique uk_order_user (order_number, user_id);
mysql唯一索引是保障数据一致性的重要防线。通过合理的索引设计,可以在保证数据质量的同时提升查询性能。实际操作中需平衡读写性能、存储空间和业务需求,定期使用explain分析索引使用效率,持续优化索引策略。
以上就是mysql添加唯一索引的常见方法的详细内容,更多关于mysql添加唯一索引的资料请关注代码网其它相关文章!
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论