1
我有MySql表和查詢,我試圖優化和有一些問題。如何使用WHERE,RANGE和SORT設置MySql表的索引?
SELECT value FROM table WHERE userid=?userid AND date <= ?date AND deleted='False' ORDER BY date DESC LIMIT 1
表:
CREATE TABLE `table` (
`tableid` int(11) NOT NULL AUTO_INCREMENT,
`userid` int(11) DEFAULT NULL,
`value` double DEFAULT '0',
`date` date DEFAULT NULL,
`deleted` enum('False','True') DEFAULT 'False',
PRIMARY KEY (`tableid`),
KEY `userid_date` (`userid`)
) ENGINE=InnoDB;
我得到以下EXPLAIN結果的查詢:
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE table ref userid_date userid_date 5 const 4 Using where; Using filesort
如果我改變也使用最新的userid_date鍵(KEY userid_date
(userid
,date
))我得到以下EXPLAIN結果:
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE table range userid_date userid_date 9 NULL 4 Using where
這樣做更好,因爲它不使用filesort,但它看起來好像只使用userid作爲鍵時的類型。你如何設置一個表的索引和這樣的查詢?使用日期類型作爲索引是否好?