【问题标题】:Mysql Group By Query Performance Very SlowMysql Group By 查询性能很慢
【发布时间】: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


【解决方案1】:

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

如果这是一个“日志”,在写入之后永远不会是UPDATEdDELETEd,那么就有可能使用数据仓库技巧。

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

【讨论】:

  • 谢谢你。你提供的链接真的很有趣。
猜你喜欢
  • 2012-08-21
  • 1970-01-01
  • 1970-01-01
  • 2017-07-13
  • 2018-09-07
  • 2021-12-26
  • 1970-01-01
  • 2019-08-21
  • 2021-02-13
相关资源
最近更新 更多