2017-05-28 30 views
0

這是SQL:mysql表的優化,只有兩個用datetime列比較

SELECT 
     f_collect_time 
    FROM 
     t_ov_meterorigvalue_a98ea7cee0b1111e48e0800163e002d36 a98ea7cee0b1111e48e0800163e002d36 
    WHERE 
     f_collect_time < '2017-05-05 00:00:00' 
    AND f_meter_id = 320679 
    ORDER BY 
     f_collect_time DESC, 
     f_meter_id 
    LIMIT 1 

我的查詢時間爲38S +

行是19093806

the index of my table is below:

the fields of my table is below

顯示創建表結果:

CREATE TABLE `t_ov_meterorigvalue_a98ea7cee0b1111e48e0800163e002d36` (
`id` int(11) NOT NULL AUTO_INCREMENT, 
`calc_time` datetime DEFAULT NULL, 
`f_coding` varchar(30) DEFAULT NULL, 
`f_collect_time` datetime DEFAULT NULL, 
`f_data` double DEFAULT NULL, 
`f_data_collection_info_id` int(11) DEFAULT NULL, 
`f_orig_value` varchar(50) DEFAULT NULL, 
`f_orig_valueid` varchar(32) DEFAULT NULL, 
`rate` double DEFAULT NULL, 
`receive_time` datetime DEFAULT NULL, 
`f_state` varchar(1) DEFAULT '0', 
`f_build_id` int(11) DEFAULT NULL, 
`f_meter_id` int(11) DEFAULT NULL, 
`f_meter_change_id` int(11) DEFAULT NULL, 
`f_meter_param_id` int(11) DEFAULT NULL, 
PRIMARY KEY (`id`), 
KEY `buildid_collecttime` (`f_build_id`,`f_collect_time`), 
KEY `meterid_collecttime_asc`  (`f_collect_time`,`f_meter_id`,`f_meter_param_id`), 
KEY `meterid_collecttime_desc` (`f_collect_time`,`f_meter_id`,`f_meter_param_id`), 
KEY `meterid_meterparamid` (`f_meter_id`,`f_meter_param_id`), 
KEY `f_meter_id` (`f_collect_time`,`f_meter_id`) USING BTREE 
) ENGINE=InnoDB AUTO_INCREMENT=19152255 DEFAULT CHARSET=utf8 

請幫我,我怎麼能優化這個可怕的查詢

+0

mysql表引擎是innodb;行格式緊湊。 – simpleman

+0

您是否可以添加該查詢的EXPLAIN輸出? –

+0

您提供的模式鏈接中沒有'meter_id'! –

回答

0

請提供SHOW CREATE TABLE。如果沒有這個,這是一個猜測。加入此指數:

INDEX(meter_id, collect_time) -- in this order 

它會做3兩件事:

  • 這將加快濾波(WHERE)。注意=部分必須是第一個。
  • 它是「覆蓋」;即所有需要的列都在索引中,從而避免索引和數據BTrees之間的彈跳。
  • 添加一個DESC,以便您有ORDER BY f_collect_time DESC, f_meter_id DESC將讓索引也處理ORDER BY而不必進行排序。但真的,爲什麼meter_id甚至在ORDER BY中提到?
+0

在進行了兩個建議的更改後,我預測的時間會少於一秒。 –

+0

是的,你是對的。我已經解決了這個問題。我添加了索引(meter_id,collect_time),並且一切正常。非常感謝你。 – simpleman