Mysql Group By 查询性能非常慢

标签 mysql performance indexing group-by innodb

我使用的是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;

如何优化这个查询?

最佳答案

它必须读取 type 索引中的所有 190 万行。这需要一些时间。 EXPLAIN FORMAT=JSON 确认它正在尽力使用给定的架构和查询。

如果这是一个在写入后从未UPDATEdDELETEd的“日志”,那么可以使用数据仓库技巧。

通过构建和增量维护汇总表,您可以将等效查询的速度提高大约 10 倍。更多 discussion .

关于Mysql Group By 查询性能非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55206682/

相关文章:

mysql - 如何改进尝试在大型数据库中查找重复条目的 MySql 查询?

javascript - JS : fastest way to return 2 numbers from function?

javascript - javascript setInterval 的内存泄漏

java - 子字符串导致字符串索引超出范围错误

java - @Enumerated 字段上的 Hibernate @Index 不起作用

mysql - 尝试通过在MySQL中添加索引来改善慢查询

mysql - Rails 分组并显示最旧和最新的值

c# - 如果 MySql C# 中不存在则插入数据

mysql - Flyway MySQL语法错误

php - 将括号留在 PHP if else 结构中会提高速度吗?