当前位置: 代码网 > it编程>数据库>Mysql > MySQL添加唯一索引的常见方法

MySQL添加唯一索引的常见方法

2026年02月01日 Mysql 我要评论
一、唯一索引的核心价值唯一索引是mysql中保证数据完整性的重要工具,它强制要求索引列的值必须唯一(允许null值,但多null值会被视为不同值)。与主键索引不同,唯一索引允许存在多个,且不隐含非空约

一、唯一索引的核心价值

唯一索引是mysql中保证数据完整性的重要工具,它强制要求索引列的值必须唯一(允许null值,但多null值会被视为不同值)。与主键索引不同,唯一索引允许存在多个,且不隐含非空约束。典型应用场景包括:

  • 用户邮箱/手机号唯一验证
  • 订单号防重复
  • 商品sku编码唯一性约束

二、建表时添加唯一索引

语法模板

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. 性能影响评估

  • 写操作性能下降(约10-30%)
  • 查询速度提升(尤其在where/order by场景)
  • 索引占用存储空间(约表大小的1.2-1.5倍)

4. 特殊场景处理

  • 忽略重复插入:使用insert ignore
insert ignore into users (username) values ('john');
  • 条件唯一索引(mysql 8.0+):
create table logs (
    id int,
    event_date date,
    unique (id, event_date)  -- 仅当event_date在最近30天时生效
) partition by range columns(event_date);

五、最佳实践建议

  1. 前缀索引优化:对长文本列使用前缀索引
alter table articles add unique (title(50));  -- 仅索引前50字符
  1. 避免过度索引:高频写入表建议不超过5个索引
  2. 监控索引碎片:定期执行optimize table重建索引
  3. 联合索引顺序:将区分度高的列放在组合索引左侧

完整示例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添加唯一索引的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com