索引簡介
索引是爲了提高數據庫查詢效率而生的。對於一些查詢多,修改少的字段很適合用索引,以提高查詢效率。如果是修改多的話,用索引會降低其效率,因爲維護這個索引表很耗時。索引分爲,主鍵索引(primary key)、唯一索引(unique index)、普通索引(index)、組合索引、全文索引。
下面先演示一下用索引和不用索引的區別。
- 查看錶中數據數量
select count(*) from 表名;
- 查看錶中索引
show index from 表名;
可以看出,這裏只有一個主鍵索引(userId)。而username字段不是索引字段。
這裏我們通過查詢username爲70000的數據,進行比較用索引和不用索引的區別。
可以清楚的看到,用索引查詢速度很快。 - 刪除索引
drop index 索引名 on 表名;
- 刪除主鍵索引,也就是刪除了該字段
alter table 表名 drop 主鍵字段名;
主鍵索引
主鍵索引,也就是我們常用的主鍵,主鍵只能有一個,但一個主鍵裏可以有多個字段。
創建表的時候創建主鍵索引
create table test(
id int(11),
name varchar(25),
primary key (id)
);
- 創建表之後給表添加主鍵索引
alter table test add constraint id primary key(id);
唯一索引
唯一索引,索引字段中的值必須是唯一的,但是允許爲空值。
- 創建表的時候創建唯一索引
create table test(
id int(11),
name varchar(25),
unique index_unique_test_name (name)
);
- 創建表之後創建唯一索引
create unique index index_unique_test_name on test(name);
- 修改表結構爲唯一索引
alter table test add unique index index_unique_test_name (name);
普通索引
普通索引是最基本的索引,僅用來加速查詢。
create table test(
id int(11),
name varchar(25),
index index_test_name (name)
);
- 創建表之後創建普通索引
create index index_test_name on test(name);
- 修改表結構爲普通索引
alter table test add index index_test_name (name);
組合索引
指多個字段上創建的索引,只有在查詢條件中使用了創建索引時的第一個字段,索引纔會被使用。使用組合索引時遵循最左前綴集合。
create table test(
id int(11),
name varchar(25),
index index_test_id_name (id,name)
);
- 創建表之後創建組合索引
create index index_test_id_name on test(id,name);
- 修改表結構爲普通索引
alter table test add index index_test_id_name (id,name);
全文索引
全文索引,是在char,varchar,text類型字段上使用全文索引。就是在一堆文字中,通過其中的某個關鍵字等,就能找到該字段所屬的記錄行,比如有"歡迎閱讀此文章"通過此文章,可能就可以找到該條記錄。
- 創建表的時候創建全文索引
create table test(
id int(11),
name varchar(25),
content text,
fulltext (text)
);
- 創建表之後創建組合索引
create fulltext index index_content on test(content);
- 修改表結構爲普通索引
alter table test add fulltext index index_content (content);