資料庫MySQL-索引
- 2020 年 3 月 27 日
- 筆記
1.6 索引
1.6.1 概述
優點
加快查詢速度
缺點:
帶索引的表在資料庫中需要更多的存儲空間 增、刪、改命令需要更長的處理時間,因為它們需要對索引進行更新
1.6.2 創建索引的指導原則
適合創建索引的列
1、該列用於頻繁搜索 2、該列用於對數據進行排序 3、在WHERE子句中出現的列,在join子句中出現的列。
請不要使用下面的列創建索引:
1、列中僅包含幾個不同的值。 2、表中僅包含幾行。為小型表創建索引可能不太划算,因為MySQL在索引中搜索數據所花的時間比在表中逐行搜索所花的時間更長
1.6.3 創建索引
1、主鍵索引:主要創建了主鍵就會自動的創建主鍵索引
2、唯一索引:創建唯一鍵就創建了唯一索引
-- 創建表的時候添加唯一索引 create table t5( id int primary key, name varchar(20), unique ix_name(name) -- 添加唯一索引 ); -- 給表添加唯一索引 mysql> create table t5( -> name varchar(20), -> addr varchar(50) -> ); Query OK, 0 rows affected (0.00 sec) mysql> create unique index ix_name on t5(name); Query OK, 0 rows affected (0.06 sec) Records: 0 Duplicates: 0 Warnings: 0 -- 通過更改表的方式創建唯一索引 mysql> alter table t5 add unique ix_addr (addr); Query OK, 0 rows affected (0.00 sec) Records: 0 Duplicates: 0 Warnings: 0
普通索引
-- 創建表的時候添加普通索引 mysql> create table t6( -> id int primary key, -> name varchar(20), -> index ix_name(name) -> ); Query OK, 0 rows affected (0.02 sec) -- 給表添加普通索引 mysql> create table t7( -> name varchar(20), -> addr varchar(50) -> ); Query OK, 0 rows affected (0.00 sec) mysql> create index ix_name on t7(name) ; Query OK, 0 rows affected (0.08 sec) Records: 0 Duplicates: 0 Warnings: 0 -- 通過更改表的方式創建索引 mysql> alter table t7 add index ix_addr(addr); Query OK, 0 rows affected (0.02 sec) Records: 0 Duplicates: 0 Warnings: 0
小結:
1、創建主鍵就會創建主鍵索引
2、創建唯一鍵就會創建唯一索引
3、創建唯一鍵的語法
--語法一 create unique [index] 索引名 on 表名(欄位名) -- 方法二 alter table 表名 add uniqe [index] 索引名(欄位名)
4、創建普通索引
-- 語法一 create index 索引名 on 表名(欄位名) -- 語法二 alter table 表名 add index 索引名(欄位名)
5、索引創建後,資料庫根據查詢語句自動選擇索引
1.6.4 刪除索引
語法:drop index 索引名 on 表名
mysql> drop index ix_name on t7; Query OK, 0 rows affected (0.01 sec) Records: 0 Duplicates: 0 Warnings: 0
