如何解决优化简单的mysql查询
| 我有一个非常简单的查询: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
无法使用ѭ4the上的索引,因为后者是表达式的一部分。如果您希望查询能够使用该索引,则需要相应地重写它:
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。