共計 1708 個字符,預計需要花費 5 分鐘才能閱讀完成。
這篇文章主要為大家展示了“Mysql 索引怎么用”,內容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓丸趣 TV 小編帶領大家一起研究并學習一下“Mysql 索引怎么用”這篇文章吧。
select …. from table where key_part1= xxx and key_part3= yyy
在這種情況下,MYSQL 只能在索引里處理掉 key_par1,而不過在索引里過濾 key_part3 的條件,除非 select 后面是 count(*) ;
這是上次測試時的表結構:
CREATE TABLE `im_message_201005_21_old` (
`msg_id` bigint(20) NOT NULL default 0 ,
`time` datetime NOT NULL,
`owner` varchar(64) NOT NULL,
`other` varchar(64) NOT NULL,
`content` varchar(8000) default NULL,
PRIMARY KEY (`msg_id`),
KEY `im_msg_own_oth_tim_ind` (`owner`,`other`,`time`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_bin;
這次我們要測試的是,先有范圍字段的條件,MYSQL 是不是能正確使用索引有效地過濾無效數據;
首先我們把索引的順序調整一下:KEY `im_msg_own_tim_oth_ind` (`owner`,`time`,`other`)
我們要測試的是當 where 條件是:owner+time+other 時,索引的工作情況如何?
(大家不如先根據自己的知識下個定論?)
我覺得大部分同學認為,字段都一樣,索引應該是能正常工作的。實際是不然。
這個測試關鍵是想看看,當查詢條件是 owner+time+other 時 , mysql 能不能在回表前,把 other 字段進行過濾;
如果不能過濾,他將與條件是 owner+time 時,產生的性能(邏輯讀)是差不多的;
select count(distinct content ) from im_message_201005_21_old
where owner = cntaobaoytazy and time = 2010-05-23 17:14:23 and time = 2010-05-30 17:14:23 ;
# 結果: 4712 行
# 產生邏輯讀:27625
select count(distinct content ) from im_message_201005_21_old
where owner = cntaobaoytazy and time = 2010-05-23 17:14:23 and time = 2010-05-30 17:14:23
and other = cnalichnahappycow ;
# 結果:0 行
# 產生邏輯讀:25516
select count(* ) from im_message_201005_21_old
where owner = cntaobaoytazy and time = 2010-05-23 17:14:23 and time = 2010-05-30 17:14:23 ;
# 結果: 4712
# 產生邏輯讀: 966
select count(* ) from im_message_201005_21_old
where owner = cntaobaoytazy and time = 2010-05-23 17:14:23 and time = 2010-05-30 17:14:23
and other = cnalichnahappycow
# 結果:0
# 產生邏輯讀: 966
從中我們發現,count(*) 這種情況,只需要通過索引去過濾,不需要回表,邏輯讀 966; 這是比較合理的值;
而第二個語句,雖然返回結果是 0 行,但使用了與第一個語句相當的邏輯讀;顯然,MYSQL 沒有合理使用索引;
以上是“Mysql 索引怎么用”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注丸趣 TV 行業資訊頻道!