我试图找出为什么MySQL数据库上的查询速度太慢。我已经阅读了有关MySQL性能,各种SO问题的各种内容,但这对我来说仍然是个谜。
我在除answer_text
我正在运行的查询是:
SELECT answer_id, COUNT(1)
FROM answers_onsite a
WHERE a.screen_id=384
AND a.timestamp BETWEEN 1462670000000 AND 1463374800000
GROUP BY a.answer_id
此查询大约需要20-30秒,然后给出结果集:
任何见解?
修改
如我所知,我的节目创建表:
CREATE TABLE 'answers_onsite' (
'id' bigint(20) unsigned NOT NULL AUTO_INCREMENT,
'device_id' bigint(20) unsigned NOT NULL,
'survey_id' bigint(20) unsigned NOT NULL,
'answer_set_group' varchar(255) NOT NULL,
'timestamp' bigint(20) unsigned NOT NULL,
'screen_id' bigint(20) unsigned NOT NULL,
'answer_id' bigint(20) unsigned NOT NULL DEFAULT '0',
'answer_text' text,
PRIMARY KEY ('id'),
KEY 'device_id' ('device_id'),
KEY 'survey_id' ('survey_id'),
KEY 'answer_set_group' ('answer_set_group'),
KEY 'timestamp' ('timestamp'),
KEY 'screen_id' ('screen_id'),
KEY 'answer_id' ('answer_id')
) ENGINE=InnoDB AUTO_INCREMENT=35716605 DEFAULT CHARSET=utf8
答案 0 :(得分:3)
ALTER TABLE answers_onsite ADD key complex_index (screen_id,`timestamp`,answer_id);
答案 1 :(得分:1)
你可以像这样使用mysql Partitioning:
alter table answers_onsite drop primary key;
alter table answers_onsite add primary key (id, timestamp) partition by HASH(id) partitions 500;
运行上述操作可能需要一段时间,具体取决于您的表格大小。
答案 2 :(得分:0)
查看WHERE子句:
Stored Procedure
我会创建一个复合索引(screen_id,answer_id,timestamp)并运行一些测试。 您也可以尝试(screen_id,timestamp,answer_id)来查看它是否表现更好。
已知BETWEEN子句比任何范围查询都慢。数百万行也是COUNT。我会每天计算一次,并将结果保存到“统计数据”中。您可以在需要时查询的表格......显然,如果您不需要实时数据。