MySQL 里给表添加索引

45 阅读1分钟

0. 引言

在 MySQL 里给表添加索引很常见,你可以根据字段的用途来决定加什么类型的索引。下面我整理了几种常用方法:


1. 普通索引(Index)

适合经常作为查询条件(WHERE)的字段:

CREATE INDEX idx_name ON files(name);

2. 唯一索引(Unique Index)

保证字段值不重复,例如 uuid

CREATE UNIQUE INDEX idx_uuid ON files(uuid);

3. 组合索引(Composite Index)

如果你经常用多个字段联合查询,比如 type + over_time

CREATE INDEX idx_type_overTime ON files(type, over_time);

4. 主键(Primary Key)

一个表只能有一个主键:

id BIGINT AUTO_INCREMENT PRIMARY KEY

5. 全文索引(Fulltext Index)

适合对长文本做模糊搜索(例如文件描述):

CREATE FULLTEXT INDEX idx_file_name ON files(name);

6. 修改表时添加索引

如果你想在 ALTER TABLE 里加:

ALTER TABLE files ADD INDEX idx_name(name);
ALTER TABLE files ADD UNIQUE idx_uuid(uuid);

7. 删除索引

DROP INDEX idx_name ON files;

建议:

  • 如果 uuid 你要保证唯一,建唯一索引:

    ALTER TABLE files ADD UNIQUE idx_uuid(uuid);
    
  • 如果 name 经常用来查找,可以加普通索引:

    ALTER TABLE files ADD INDEX idx_name(name);
    
  • 如果 over_time 经常用来清理过期,可以加索引:

    ALTER TABLE files ADD INDEX idx_over_time(over_time);