MySQL-索引03
- 主鍵索引
- 普通索引
- 唯一索引
- 聯合(組合)索引
- 聯合主鍵索引
- 聯合普通索引
- 聯合唯一索引
-------------------
- 主鍵索引
create tabel tb1(
id int auto_increment priamry key,
name char(32) not null,
age int not null
)engine=innodb default utf8;
create tabel tb1(
id int auto_increment,
name char(32) not null,
age int not null,
primary key (id)
)engine=innodb default utf8;
添加主鍵:
alter table 表名 add primary key(列名)
刪除主鍵:
alter table 表名 drop primary key;
alter table 表名 modify 列名 int, drop primary key;
- 普通索引
create table tb1(
id int auto_increment primary key,
name char(32) not null,
age int(10) not null,
index ix_name (name)
)engine=innodb default charset utf8;
create index ix_name on tb1(name);
drop index ix_name on tb1;
show index from tb1;
create index ix_name on tb1(name(2));
如果建立索引的對象是二進制blob()和text類型時,必須像上面這一在括號內指定長度。
- 唯一索引
- 唯一約束(不能重複)和加速索引的功能
- 唯一索引和主鍵索引的區別:unique 可以爲空null,而primary key 不能爲空
create table tb1(
id int auto_increment primary key,
name char(32) not null,
age int(10) not null,
email char(32) not null,
unique ui_email (email)
)
create unique index ui_email on tb1(email);
drop unique index ui_email on tb1;
- 組合索引
create unique index ui_index on tb1(name,email);
drop unique index ui_index on tb1;
如上創建組合索引之後,查詢:
name and email -- 使用索引
name -- 使用索引
email -- 不使用索引
注意:對於同時搜索n個條件時,組合索引的性能好於多個單一索引合併。