mysql基礎(三)

來源:互聯網
上載者:User

標籤:font   主鍵索引   唯一索引   play   ges   指定   合成   odi   建立   

索引

索引,是資料庫中專門用於協助使用者快速查詢資料的一種資料結構。類似於字典中的目錄,尋找字典內容時可以根據目錄尋找到資料的存放位置,然後直接擷取即可。

 

索引是在資料庫中再建立一個檔案。

有索引和無索引查詢時間差距巨大。

全表掃描效率最低。

上萬條資料用樹型結構,最少14此就搞定。

 

 

常見索引分類:
  • 普通索引
  • 唯一索引
  • 主鍵索引
  • 複合式索引
  • 全文索引

 

普通索引 只能協助尋找
唯一索引 只能協助尋找,內容不允許重複,可以有null
主鍵索引 只能協助尋找,內容不允許重複,不允許null,一張表只能有一個主鍵
複合式索引 多列共同組成索引,普通多列索引(name,email)
全文索引 分詞、斷句(依據逗號,空格),對中文支援不好,中文全文索引不用mysql的引擎。常用solr,lucence,sphix

 

 

 

 

 

 

 

1、普通索引

普通索引僅有一個功能:加速查詢

 

建立普通索引

 

View Code

 

 

 

建立表後再加索引create index index_name on table_name(column_name)

 

刪除索引drop index_name on table_name;

 

查看索引
show index from table_name;

注意:對於建立索引時如果是BLOB 和 TEXT 類型,必須指定length。

 

 

2、唯一索引

  唯一索引有兩個功能:加速查詢 和 唯一約束(可含null)

  

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))建立表 + 唯一索引
View Code

 

建立唯一索引create unique index 索引名 on 表名(列名)

 

刪除唯一索引drop unique index 索引名 on 表名

 

 

3、主鍵索引

 

 主鍵有兩個功能:加速查詢 和 唯一約束(不可含null)

 

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))ORcreate table in1(    nid int not null auto_increment,    name varchar(32) not null,    email varchar(64) not null,    extra text,    primary key(ni1),    index ix_name (name))建立表 + 建立主鍵
View Code

 

建立主鍵alter table 表名 add primary key(列名);

 

刪除主鍵alter table 表名 drop primary key;alter table 表名  modify  列名 int, drop primary key;

 

 

 

4、複合式索引

 複合式索引是將n個列組合成一個索引

其應用情境為:頻繁的同時使用n列來進行查詢,如:where n1 = ‘alex‘ and n2 = 666。

 

create table in3(    nid int not null auto_increment primary key,    name varchar(32) not null,    email varchar(64) not null,    extra text)建立表
View Code

 

 

建立複合式索引create index ix_name_email on in3(name,email);

 

 

 

注意:對於同時搜尋n個條件時,複合式索引的效能好於多個單一索引合并。

 

mysql基礎(三)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.