簡體   English   中英

優化簡單的mysql查詢

[英]optimizing simple mysql query

我有一個非常簡單的查詢:

SELECT cp.`id_connections`
FROM `connections_page` cp
WHERE cp.`time_end` IS NULL
AND TIME_TO_SEC(TIMEDIFF(NOW(), cp.`time_start`)) < 900
GROUP BY cp.`id_connections`

對於一個非常簡單的表:

CREATE TABLE IF NOT EXISTS `ps_connections_page` (
`id_connections` int(10) unsigned NOT NULL,
`id_page` int(10) unsigned NOT NULL,
`time_start` datetime NOT NULL,
`time_end` datetime DEFAULT NULL,
PRIMARY KEY (`id_connections`,`id_page`,`time_start`),
KEY `time_end` (`time_end`),
KEY `id_connections` (`id_connections`),
KEY `id_page` (`id_page`),
KEY `time_start` (`time_start`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

大約有250萬行 ,執行需要2到6秒 (mysql 5.1.54-log)

EXPLAIN EXTENDED說:

id      select_type    table    type    possible_keys   key         key_len ref     rows    filtered    Extra
1       SIMPLE         cp       ref     time_end        time_end    9       const   1497890 100.00      Using where; Using temporary; Using filesort

看看執行計划,索引使用有問題,但我無法弄清楚。 那么:如何通過改變數據結構來加速這個查詢(我可以更改查詢和/或索引,但不能更改列)?

這部分:

TIME_TO_SEC(TIMEDIFF(NOW(), cp.`time_start`)) < 900

無法在time_start上使用索引,因為后者是表達式的一部分。 如果您希望查詢能夠使用該索引,則需要相應地重寫它:

time_start < something_constant

此外,您可以通過在幾個where / group by字段中添加索引來獲益:

key(time_start, time_end, id_connections)

首先你不需要使用別名cp

第二,我會嘗試做一個子選擇來減少時間計算

嘗試這個讓我知道它是否有所作為

SELECT id_connections
FROM (SELECT id_connections FROM connections_page WHERE time_end IS NULL))
WHERE TIME_TO_SEC(TIMEDIFF(NOW(), time_start)) < 900
GROUP BY id_connections

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM