1. 程式人生 > >MySQL--索引

MySQL--索引

mysql--索引

- | 索引的作用
1、約束
2、加速查找
- | 為什麽索引可以這麽快?
為什麽索引可以這麽快?
name列建立索引
創建一個文件,name列所有數據拿出來
通過數字來標記,在一種特殊的數據結構中查找
層級越多,越快
(B-tree索引)
| 索引的種類
-
| 普通索引
-- 加速查找
1-創建表-創建索引
--創建表的同時創建索引
create table in1(
    nid int not bull auto_increment primary key,
    name varchar(32) not null,
    email varchar(64) not null,
    index ix_name (name)
);
2-創建索引
-- 在創建表之後再去創建索引
create index 索引名 on 表名(列名)
create index index_name on table_name(column_name)
3-刪除索引
# error
drop index index_name on table_name;
4-查看索引
show index from table_name
-
| 唯一索引
-- 加速查找,約束列數據不能重復,null
1-創建表-創建索引
-- 創建表的同時創建唯一索引
create table in1(
    nid int not null auto_increment primary key,
    name varchar(32) not null,
    email varchar(64) not null,
    extra text,
    unique ix_name (name)
);
2-創建索引
-- 在創建表之後再取創建索引
create unique index 索引名 on 表名(列名)
3-刪除索引
drop unique index 索引名 on 表名
-
| 主鍵索引
-- 加速查找,約束列數據不能重復,不能null
1-創建表-創建索引
create table in1(
    nid int not null auto_increment primary key,
    name varchar(32) not null,
    email varchar(64) not null,
    extra text,
    index ix_name (name)
)
OR
create table in1(
    nid int not null auto_increment,
    name varchar(32) not bull,
    email varchar(64) not null,
    extra text,
    primary key(nid),
    index ix_name (name)
)
2-創建主鍵
alter table 表名add primary key(列名)
3-刪除主鍵
alter table 表名 drop primary key;
alter table 表名 modify 列名 int, drop primary key;
-
| 組合索引
-- 多列可以創建一個索引文件
2-聯合唯一索引:
    有約束,兩列數據都不相同,才能插入,不然報錯
# 查找:最左匹配(最左前綴)
select * from tb1 where name = ‘alex‘
select * from tb1 where name = ‘alex‘ and pwd = ‘123‘
select * from tb1 where pwd = ‘123‘  # 不會走索引
- | 索引的優缺點
--增刪改慢,耗費資源
--查找快
- | 覆蓋索引
-- 下例中nid設置了索引
select * from tb where nid=1;
# 先去索引中找
# 再取數據表中找
select nid from tb where nid < 10;
-- 情況應用上了索引,並且不用去數據庫中操作,覆蓋索引
# 只需要在索引表中就能獲取數據
- | 合並索引
-- 列: nid, name(單獨索引) ,email(單獨索引), pwd
    select * from tb where name = ‘alex‘
    select * from tb where email = ‘[email protected]‘
    select * from tb where name = ‘alex‘ or email = ‘[email protected]‘
    # 合並索引
- | 執行計劃
-- 相對比較準確的表達出當前SQL運行的狀況
-- 是否走索引,走的是什麽索引
1、 explain SQL語句
    type:ALL   -- 全數據表掃描
    type:index    -- 全索引表掃描
2、limit
    select * from tb1 where email = ‘123‘;
    select * from tb1 where email limit = 1;
----- SQL: ALL、Index, 都是
有優化的余地 -----
3、range
    執行範圍查詢,type是range,
    如果沒有索引type是ALL,全表掃描
註意:!= 和 > 符號,不走索引

MySQL--索引