我很難弄清楚爲什麼類似查詢的執行時間相差很遠。我有一個簡單SELECT
這樣的查詢:奇怪的MySQL SELECT執行時間
SELECT
`location_id`,
`datetime`,
`year`,
`month`,
`load`
FROM load_report_rows
WHERE location_id = '16583'
AND load_report_id = '1'
AND year = '2010'
該查詢在0.1837秒歡快地運行,但如果我改變location_id
爲「18260」,查詢突然發生2.7012秒。在WHERE
子句中使用的所有三個字段都被編入索引,並且兩個查詢都完全返回8760行。該EXPLAIN
該查詢返回以下信息:
id 1
select_type SIMPLE
table load_report_rows
type index_merge
possible_keys load_report_id,location_id,year
key location_id,load_report_id,year
key_len 4,4,4
ref NULL
rows 3349
extra using intersect(location_id,load_report_id,year); using where
MySQL查詢分析器提供每個查詢的以下方面:
+--------------------------------+----------+----------+
| Status | Query 1 | Query 2 |
+--------------------------------+----------+----------+
| starting | 0.000023 | 0.000023 |
| checking query cache for query | 0.000072 | 0.000068 |
| checking permissions | 0.000010 | 0.000068 |
| opening tables | 0.000012 | 0.000012 |
| system lock | 0.000005 | 0.000004 |
| table lock | 0.000008 | 0.000008 |
| init | 0.000050 | 0.000026 |
| optimizing | 0.000030 | 0.000014 |
| statistics | 0.000461 | 0.001048 |
| preparing | 0.000022 | 0.000043 |
| executing | 0.000003 | 0.000004 |
| sending data | 0.100939 | 2.649942 |
| end | 0.000013 | 0.000040 |
| end | 0.000004 | 0.000004 |
| query end | 0.000004 | 0.000004 |
| freeing items | 0.000012 | 0.000013 |
| closing tables | 0.000008 | 0.000008 |
| logging slow query | 0.000002 | 0.000003 |
| cleaning up | 0.000006 | 0.000005 |
+--------------------------------+----------+----------+
的sending data
階段與第二查詢顯著需要較長的時間。包含哪些步驟?這裏的表結構爲相關領域是否有幫助:
`id` int(11)
`load_report_id` int(11)
`location_id` int(11)
`datetime` datetime
`year` int(4)
`month` int(2)
`load` decimal(16,8)
PRIMARY KEY (`id`)
KEY `load_report_id` (`load_report_id`)
KEY `location_id` (`location_id`)
KEY `year` (`year`)
KEY `month` (`month`)
任何想法可能會導致第二個查詢跑這麼慢?
這樣做的伎倆,我的總運行時間從5分鐘下降到44秒。刪除引號似乎沒有任何區別。我猜想當MySQL在執行它之前優化查詢時,字符串會在處理之前自動轉換爲整數。謝謝! – 2010-11-03 23:39:47