【发布时间】:2019-03-17 11:46:00
【问题描述】:
我正在使用 Mysql 5.7 我有一张有 1 900 516 行的表格。 我的查询对已编入索引但仍需要时间执行的列执行分组。以下是我的查询、执行计划和表架构。
select `type`,count(`type`)
from templog
group by `type` ;
查询解释格式
{
"query_block": {
"select_id": 1,
"cost_info": {
"query_cost": "376984.80"
},
"grouping_operation": {
"using_filesort": false,
"table": {
"table_name": "templog",
"access_type": "index",
"possible_keys": [
"templog_type_idx"
],
"key": "templog_type_idx",
"used_key_parts": [
"type"
],
"key_length": "1",
"rows_examined_per_scan": 1856244,
"rows_produced_per_join": 1856244,
"filtered": "100.00",
"using_index": true,
"cost_info": {
"read_cost": "5736.00",
"eval_cost": "371248.80",
"prefix_cost": "376984.80",
"data_read_per_join": "84M"
},
"used_columns": [
"templogid",
"type"
]
}
}
}
}
表架构
CREATE TABLE `templog` (
`templogid` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`userid` bigint(12) unsigned NOT NULL,
`type` tinyint(3) NOT NULL DEFAULT '0',
`location` json DEFAULT NULL,
`ip` int(4) unsigned DEFAULT NULL,
`createdat` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`status` tinyint(3) unsigned NOT NULL DEFAULT '1',
PRIMARY KEY (`templogid`),
KEY `templog_type_idx` (`type`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1900516 DEFAULT CHARSET=utf8;
如何优化这个查询?
【问题讨论】:
-
这需要多长时间?类型真的被索引了吗?它在您的架构中不可见。
-
执行计划对我来说看起来不错(唯一的次要微优化是使用 int 而不是 bigint 作为主键,如果这是您的数据的一个选项)。你能澄清一下“慢”吗,因为慢是相对的?
标签: mysql performance indexing group-by innodb