MySQL 索引

46 阅读1分钟

查询索引

-- 方式1
show index from 表名
-- 方式2
show indexes from 表名
-- 方式3
show keys from 表名
-- 方式4
desc 表名

添加索引

-- 添加唯一索引
create unique index 索引名 on 表名 (列名)
-- 添加普通索引方法1
create index 索引名 on 表名 (列名)
-- 添加普通索引方法2
alter table 表名 add index 索引名 (列名)
-- 添加主键索引方法1
alter table 表名 add primary key (列名)
-- 添加主键索引方法2 创建表的时候直接指定创建主键索引
create table 表名 (
    id int primary key,
    name varchar(20) not null
)
-- 添加主键索引方法3 创建表的时候直接指定创建主键索引,可以多列
create table 表名 (
    id int,
    name varchar(20) not null,
    age int,
    primary key (id, name)
)

删除索引

-- 删除索引
drop index 索引名 on 表名
-- 删除主键索引
alter table 表名 drop primary key

备注: 修改索引方式,先删除索引,再添加索引。