1. 程式人生 > 其它 >mysql詳解13:索引

mysql詳解13:索引

索引:儲存在磁碟中
影響效能

建立索引
EXPLAIN select * from student where state ="CA";//查詢並檢視掃描的條數
create INDEX idx_state on student(state); //在該欄位上建立索引 再查詢
建立索引後再查詢 掃描的條數減少

檢視索引
ANALYZE TABLE customers; //可以讓索引的統計值不再是估值,更加準確
show INDEX in student;
二級索引
主鍵和外來鍵都會自動建立索引

前置索引:只包含列的前幾個字母或者列字首
CREATE INDEX idx_lastname on customers (last_name(20));

select count(DISTINCT LEFT(last_name,1)),
count(DISTINCT LEFT(last_name,5)),
count(DISTINCT LEFT(last_name,10)) from customers;
//25 966 996 所以選5


全文索引
select * from posts where title like "%react redux%" or body like "%react redux%";

create FULLTEXT INDEX idx_titile_body on posts(titile,body);
select * MATCH(title,body) AGAINST('react redux')
from posts
where MATCH(title,body) AGAINST('react redux');
//按照搜尋相關性排序

select * MATCH(title,body) AGAINST('react redux')
from posts
where MATCH(title,body) AGAINST('react -redux +form ' IN BOOLEAN MODE);
表示結果中必須含有react form 排除redux
"handling a form" 表示搜尋這個短語

複合索引

複合索引
允許對多鍵建立索引 最多可以16列
create index idx_state_points on customers(states,point);

Drop index idx_state on customers;

複合索引中列的順序
正常情況下:要把種類多的放在前面

Select customer_id
From customers
Use index(idx_lastname_state)
Where state like ‘a%’ and last_name like ‘a%’;

要搜尋所有的州和名字。所以複合索引把名字放前面

Select customer_id
From customers
Use index(idx_lastname_state)
Where state =‘CA’ and last_name like ‘a%’;

因為=的約束更強,所以把州排在前面效率更高。

複合索引以state開頭的對於單列points 沒有效率

當索引無效
EXPLAIN SELECT customer_id
from customers where state =‘CA’ or points >1000;
此時idx_state_points 不起作用

EXPLAIN SELECT customer_id from customers where points+10>2010;

想要使用索引 必須把列單獨表示

索引排序
複合索引按照列的順序進行排序
如果查詢中的排序不包含在索引內,將不使用索引
另外多列排序必須是要與索引中保持一致 或者完全相反
不能單獨為第二列排序 除了第一列指定

覆蓋索引
索引中 只放了主鍵和包含的列 查詢其他列將不使用索引

維護索引
重複索引
建立新索引之前檢視是否會出現多餘索引
確保刪除重複索引 多餘索引 和未使用的索引
(A,B)
X 多餘索引
(B)


授權


GRANT SELECT ,INSERT, UPDATE,DELETE,EXECUTE ON sql_store.*
TO moon_app;

SHOW GRANTS FOR John;

REVOKE CREATE VIEW
ON sql_store.*
From moon_app;