MySql索引總結

2021-12-30 11:10:59 字數 1972 閱讀 7292

這幾天去面試總是被問到索引的問題,今天總結了一下

1. 普通索引

這是最基本的索引,它沒有任何限制,比如上文中為title欄位建立的索引就是乙個普通索引,myiasm中預設的btree型別的索引,也是我們大多數情況下用到的索引

直接建立索引

create index index_name on table(column(length))

–修改表結構的方式新增索引

alter table table_name add index index_name on (column(length))

–建立表的時候同時建立索引

create table `table` (

`id` int(11) not null auto_increment ,

`title` char(255) character set utf8 collate utf8_general_ci not null ,

`content` text character set utf8 collate utf8_general_ci null ,

`time` int(10) null default null ,

primary key (`id`),

index index_name (title(length))

)–刪除索引

drop index index_name on table2. 唯一索引

與普通索引類似,不同的就是:索引列的值必須唯一,但允許有空值(注意和主鍵不同)。如果是組合索引,則列值的組合必須唯一,建立方法和普通索引類似。

--建立唯一索引

create unique index indexname on table(column(length))

–-修改表結構

alter table table_name add unique index_name on(column(length))

--建立表的時候就建立索引

create table table_name(

id int(2) not null,

name varchar(100),

unique indexname(name(length))

)3. 全文索引(fulltext)

mysql從3.23.23版開始支援全文索引和全文檢索,fulltext索引僅可用於 myisam 表;他們可以從char、varchar或text列中作為create table語句的一部分被建立,或是隨後使用alter table 或create index被新增。////對於較大的資料集,將你的資料輸入乙個沒有fulltext索引的表中,然後建立索引,其速度比把資料輸入現有fulltext索引的速度更為快。不過切記對於大容量的資料表,生成全文索引是乙個非常消耗時間非常消耗硬碟空間的做法。

建立表的適合新增全文索引

create table `table` (

`id` int(11) not null auto_increment ,

`title` char(255) character set utf8 collate utf8_general_ci not null ,

`content` text character set utf8 collate utf8_general_ci null ,

`time` int(10) null default null ,

primary key (`id`),

fulltext (content)

);–修改表結構新增全文索引

alter table article add fulltext index_content(content)

–直接建立索引

create fulltext index index_content on article(content)就在這裡介紹一些比較常見的索引例子

mysql 索引總結 mysql索引總結

mysql中每乙個表都有乙個聚簇索引clusted index,該所索引是預設建立的,除此之外的表上的每乙個非聚簇索引都是二級索引,又叫輔助索引 secondary indexes 以innodb來說,每個innodb表具有乙個特殊的索引稱為聚集索引,如果您的表上定義有主鍵,該主鍵索引是聚集索引,如...

mysql次級索引 MySQL 索引總結

1 索引是做什麼的?想象一下,你面前有本詞典,資料就是書的正文內容,你就是那個cpu,而索引,則是書的目錄 索引用於快速找出在某個列中有一特定值的行。不使用索引,mysql必須從第1條記錄開始然後讀完整個表直到找出相關的行。表越大,花費的時間越多。如果表中查詢的列有乙個索引,mysql能快速到達乙個...

mysql 索引總結

索引用來快速地尋找那些具有特定值的記錄,所有mysql索引都以b 樹的形式儲存。如果沒有索引,執行查詢時mysql必須從第乙個記錄開始掃瞄整個表的所有記錄,直至找到符合要求的記錄。表裡面的記錄數量越多,這個操作的代價就越高。如果作為搜尋條件的列上已經建立了索引,mysql無需掃瞄任何記錄即可迅速得到...