2011-07-08 43 views
3

表:如何爲此SQL查詢創建索引?

CREATE TABLE `deal` (
    `id` int(11) NOT NULL default '0', 
    `site` int(11) NOT NULL default '0', 
    `time` bigint(13) NOT NULL default '0', 
    PRIMARY KEY (`id`), 
    KEY `site` (`site`), 
    KEY `time` (`time`,`site`) 
) TYPE=MyISAM 

SQL查詢:

select * from `deal` where time>0 && site=8 

創建索引:time此查詢,

偏偏這個查詢總是使用索引:site

explain select * from `deal` where time>0 && site=8 

輸出:

table type possible_keys key key_len ref rows Extra 

deal  ref  site,time  site 4   const 1  Using where 

回答

5

您需要創建綜合指數site + time(是的,爲了事宜)。

因此刪除這兩個指標sitetime現在,創建2個:

  1. KEY site (site, time)
  2. KEY time (time)
+0

感謝zerkms,'鍵的網站(網站,時間)'可以完全替代'鍵網站(site)'? (我也需要'select * from deal where site = 123') – Koerr

+1

@ Zenofo:是的,它被稱爲「最左邊」。所以對於索引'a + b + c',你不需要索引'a'和'a + b',因爲它的左邊部分覆蓋了它們 – zerkms