【问题标题】:Indexing for group by + SUM query on mysqlmysql上的group by + SUM查询的索引
【发布时间】:2011-08-26 14:08:41
【问题描述】:

我有一个具有以下架构的表:

    CREATE TABLE `wordtrend` (
      `oid` bigint(20) NOT NULL AUTO_INCREMENT,
      `monitorId` bigint(20) DEFAULT NULL,
      `nGram` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
      `nGramWord` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
      `negatives` bigint(20) DEFAULT NULL,
      `neutrals` bigint(20) DEFAULT NULL,
      `positives` bigint(20) DEFAULT NULL,
      `total` bigint(20) DEFAULT NULL,
      `trendCut` datetime DEFAULT NULL,
      PRIMARY KEY (`oid`)
    ) ENGINE=MyISAM 
      AUTO_INCREMENT=358539 
      DEFAULT CHARSET=utf8  COLLATE=utf8_unicode_ci

是否可以创建索引以有效地运行以下查询?

SELECT nGram
     , nGramWord
     , SUM(total) AS sTotal
     , SUM(positives)
     , SUM(negatives)
     , SUM(neutrals) 
FROM WordTrend 
WHERE monitorId = 21751021 
  AND trendCut >= '2011-01-01 00:00:00' 
GROUP BY nGram
       , nGramWord 
ORDER BY sTotal DESC

我们已经尝试了以下方法:

KEY `RollupIndex` (`monitorId`,`trendCut`)
KEY `RollupIndex2` (`monitorId`,`nGram`,`trendCut`)

但我们在额外的列上得到“使用 where;使用临时;使用文件排序”。提前致谢。

【问题讨论】:

  • 查询返回了多少行?运行需要多少时间?
  • 我很好奇这两个查询会显示什么:SELECT COUNT(DISTINCT nGram) FROM WordTrendSELECT COUNT(DISTINCT nGram, nGramWord) FROM WordTrend
  • (警告:如果没有(nGram,nGramWord)上的索引,它们可能真的很慢

标签: mysql indexing group-by


【解决方案1】:
  1. 您按没有索引的列排序,因此您可以使用临时获得信息;使用文件排序
  2. 在哪里使用; - 在 where 子句中使用带或不带索引的 where 进行搜索。

【讨论】:

    【解决方案2】:

    您使用排序 - 'ORDER BY sTotal DESC',因此sTotal 字段上的索引可能会有所帮助。

    【讨论】:

    • sTotal 是 SUM(total) 列的名称。我认为你不能索引 sTotal,对吧?
    【解决方案3】:

    尝试不同的 KEY 组合(nGramnGramWordtotal)。

    【讨论】:

      【解决方案4】:

      为什么不使用EXPLAIN 来获取有关性能的有用信息并优化您的查询?!

      【讨论】:

        猜你喜欢
        • 2018-06-02
        • 2020-05-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-26
        • 1970-01-01
        • 1970-01-01
        • 2013-08-07
        相关资源
        最近更新 更多