索引優點:
1,一般是作用於where子句所給出的條件相匹配的行
一是在關聯操作中與其他數據表所匹配的行。
2,對於使用mix() 和max()函數的查詢的列
3,經常使用order by 和group by的列
4,索引可以加快查詢速度,不用掃描整個表
索引缺點
1,索引雖然加快查詢的速度,但是會降低寫入操作,比如插入,修改,刪除數據
2,索引要占據磁盤空間,索引越多占據空間越大,
對myisam表來說,大量索引一個數據表可能使索引文件比數據文件更快達到它的尺寸上限
對innodb來說,全部innodb數據表分享同一個存儲空間,添加索引會是表空間用於存儲的空間變小
散列索引對於“=”和“<=>”操作進行匹配時速度極快,但是對於范圍查找和比較查找比較慢
B樹索引對於 <,<=,>,>=,=<>,!= 和 between操作進行的查詢效率較高,而且對於純字符串開頭,而不是通配符開頭的,B樹可以使用like操作符進行模式匹配
慢查詢
mysqldumpsqlow
1,主鍵索引
2,唯一索引
3,常規索引
4,全文索引
創建索引,默認是asc排序,使用btree
create index index_name on tbl_name (column asc{default}|desc)
如果相關表已經使用Memory引擎建立,則使用hash索引
create index index_name using btree|hash on on tbl_name (column asc)
創建復合索引
create index index_name on tbl_name (column1,column2)
create table carts(
cartid int not null,
userid,
bookid,
number,
primary key (cartid),
key index_name(userid,bookid)
);
唯一索引
create unique index index_name on tbl_name (column)
可選項:unique |fulltext | spatial
create table cate(
cateid int not null auto_increment primary key,
catename varchar not null unique
catemenu varchar not null fulltext
);
使用alert語句添加索引
alert table tbl_name add index index_name using btree (column)
創建表時添加索引
create table tbl_name(
column1 int not null
primary key,
column2 int not null,
column3 smallint not null,
index index_name(column)
unique indxe index_name using hash (column2,column3)
)
全文索引
全文搜索同MATCH()函數一起執行。
mysql> CREATE TABLE articles (
mysql> CREATE TABLE articles (
id INT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY,
title VARCHAR(200),
body TEXT,
FULLTEXT (title,body)
);
1,任何過於短的詞都會被忽略。 全文搜索所能找到的詞的默認最小長度為 4個字符。
2,
停止字中的詞會被忽略。禁用詞就是一個像“the” 或“some” 這樣過於平常而被認為是不具語義的詞。存在一個內置的停止字, 但它可以通過用戶自定義列表被改寫。
3,
單詞 出現在50%的行中。 它被列入停止字。
select book_name ,price from books where Match(column) against("string");
drop index
index_name on tbl_name
視圖
視圖是一種虛擬表,他的行為和數據表一樣,但是不包含真正的數據。
創建視圖語法
create view <view name>[<column list>] as <table expression> [with [cassaded | local ] check option]
創建視圖
create view view_name as select column1,column2 from tbl_name where xxx>xx
創建視圖時指定列
create view view1 (va1,va2,va3) as select va1,va2,va3 from tbl where va1<num;
創建索引時可以使用表聯接
creaet view vst as select id,name,date,score category from grade_event inner join score inner join stu on grade_event.id=score.event_id and score.id =stu.id
創建索引時可以把數學運行放到視圖的一個 列中
create view view_demo select name, birth,death timstampdiff(year,birth ,death) as age from tbl