1. 程式人生 > 實用技巧 >MySQL資料庫之索引

MySQL資料庫之索引

索引

  • 概述
    • 優點
      • 加快查詢速度
    • 缺點
      • 帶索引的表在資料庫中需要更多的儲存空間
      • 增、刪、改命令需要更長的處理時間,因為它們需要對索引進行更新

建立索引的指導原則

  • 適合建立索引的列

    • 該列用於頻繁搜尋
    • 該列用於對資料進行排序
    • 在WHERE子句中出現的列,在join子句中出現的列
  • 請不要使用下面的列建立索引

    • 列中僅包含幾個不同的值
    • 表中僅包含幾行。為小型表建立索引可能不太划算,因為MySQL在索引中搜索資料所花的時間比在表中逐行搜尋所花的時間更長

建立索引

  • 主鍵索引

    • 主要建立了主鍵就會自動的建立主鍵索引
  • 唯一索引

    • 建立唯一鍵就建立了唯一索引

唯一索引與普通索引

  • 說明

    • 建立主鍵就會建立主鍵索引
    • 建立唯一鍵就會建立唯一索引
    • 索引建立後,資料庫根據查詢語句自動選擇索引
  • 建立唯一鍵的語法

    • create unique [index] 索引名 on 表名(欄位名)
    • alter table 表名 add uniqe [index] 索引名(欄位名)
  • 建立普通索引的語法

    • create index 索引名 on 表名(欄位名)
    • alter table 表名 add index 索引名(欄位名)

唯一索引的建立

  • 建立表的時候新增唯一索引
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`

刪除索引

  • 語法
    • drop index 索引名 on 表名
mysql> drop index ix_name on t7;
# `Query OK, 0 rows affected (0.01 sec)`
# `Records: 0  Duplicates: 0  Warnings: 0`