it编程 > 数据库 > Mysql

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

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 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);

五、最佳实践建议

  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)

您想发表意见!!点此发布评论

推荐阅读

MySQL中REPLACE INTO语句原理、用法与最佳实践

02-01

MySQL数据表修改与管理的完整指南

02-01

一文详解MySQL表数据完整性的8大约束机制

02-01

解决登录MySQL时提示ERROR 2003 (HY000): Can‘t connect to MySQL server on ‘localhost:3306‘ (10061)

01-31

MySQL基础增删查改操作详解

01-31

MySQL对前N条数据求和的几种方案

01-31

猜你喜欢

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

发表评论