MySQL Index 索引提示

2021-10-10 11:10:17 字數 3000 閱讀 4541

sql 提示(sql hint)是優化資料庫的乙個重要手段,簡單來說就是在sql 語句中加入一些人為的提示來達到優化操作的目的。

在查詢語句中表名的後面,新增use index 來提供希望mysql 去參考的索引列表,就可以讓mysql 不再考慮其他可用的索引。

mysql>

explain

select

*from sales2 use

index

(ind_sales2_id)

where id =3;

****

****

****

****

****

****

***1.

row***

****

****

****

****

****

****

id: 1

select_type: ******

table: sales2

type: ref

possible_keys: ind_sales2_id

key: ind_sales2_id

key_len: 5

ref: const

rows: 1

extra: using

where

1row

inset

(0.00 sec)

.

如果使用者只是單純地想讓mysql 忽略乙個或者多個索引,則可以使用ignore index 作為hint。同樣是上面的例子,這次來看一下查詢過程忽略索引ind_sales2_id 的情況:

mysql>

explain

select

*from sales2 ignore

index

(ind_sales2_id)

where id =3;

****

****

****

****

****

****

***1.

row***

****

****

****

****

****

****

id: 1

select_type: ******

table: sales2

type: all

possible_keys: null

key: null

key_len: null

ref: null

rows: 1000

extra: using

where

1row

inset

(0.00 sec)

.

為強制mysql 使用乙個特定的索引,可在查詢中使用force index 作為hint。例如,當不強制使用索引的時候,因為id 的值都是大於0 的,因此mysql 會預設進行全表掃瞄,而不使用索引,如下所示:

mysql>

explain

select

*from sales2 where id >0;

****

****

****

****

****

****

***1.

row***

****

****

****

****

****

****

id: 1

select_type: ******

table: sales2

type: all

possible_keys: ind_sales2_id

key: null

key_len: null

ref: null

rows: 1000

extra: using

where

1row

inset

(0.00 sec)

但是,當使用force index 進行提示時,即便使用索引的效率不是最高,mysql 還是選擇使用了索引,這是mysql 留給使用者的乙個自行選擇執行計畫的權力。加入force index 提示後再次執行上面的sql:

mysql>

explain

select

*from sales2 force

index

(ind_sales2_id)

where id >0;

****

****

****

****

****

****

***1.

row***

****

****

****

****

****

****

id: 1

select_type: ******

table: sales2

type: range

possible_keys: ind_sales2_id

key: ind_sales2_id

key_len: 5

ref: null

rows: 1000

extra: using

where

1row

inset

(0.00 sec)

.

sql 優化問題是資料庫效能優化最基礎也是最重要的乙個問題,實踐表明很多資料庫效能問題都是由不合適的sql 語句造成。本章通過例項描述了sql 優化的一般過程,從定位乙個有效能問題的sql 語句到分析產生效能問題的原因,最後到採取什麼措施優化sql 語句的效能。另外還介紹了優化sql 語句經常需要考慮的幾個方面,比如索引、表分析、排序等。

索引的設計可以遵循一些已有的原則,建立索引的時候請盡量考慮符合這些原則,便於提公升索引的使用效率,更高效地使用索引。

mysql index 資訊 MySQL 索引

mysql索引的建立對於mysql的高效執行是很重要的,索引可以大大提高mysql的檢索速度。打個比方,如果合理的設計且使用索引的mysql是一輛蘭博基尼的話,那麼沒有設計和使用索引的mysql就是乙個人力三輪車。索引分單列索引和組合索引。單列索引,即乙個索引只包含單個列,乙個表可以有多個單列索引,...

Oracle index 索引提示解析

使用 hints 時,在某些情況下,為了確保讓優化器產生最優的執行計畫,我們可能指定全套的 hints oracle 索引提示,oracle index 提示,oracle index tips oracle index 優化,oracle index 提示。指示優化器的方法與目標的 hints a...

SQLSERVER中忽略索引提示

當我們想讓某條查詢語句利用某個索引的時候,我們一般會在查詢語句裡加索引提示,就像這樣 複製 如下 select id,name from tb with index ix xttrace bal where bal 100 當在生產環境裡面,由於這個索引提示的原因,優化器一般不會再去考慮其他的索引,...