减少查询的执行时间

时间:2014-01-29 09:22:57

标签: mysql sql performance innodb

我想减少mysql中查询所花费的时间。

有三个表说

  1. A~600k行,
  2. B~2K行,
  3. C~100K行
  4. 每个有2列。

    1. A有一列用于聚合,另一列用于与表B连接。
    2. B有一列用A连接,另一列用C
    3. 连接
    4. C有一列要与B连接,另一列要分组。
    5. 减少运行时间的索引计划应该是什么。截至目前,它使用临时表,然后文件排序。有什么方法可以避免临时表格。

      示例查询:

       SELECT
            sum(`revenue_facts`.`total_price`) AS `m0`
      FROM 
          `category_groups` AS `category_groups`,
          `revenue_facts` AS `revenue_facts`,
          `dim_products` AS `dim_products`
      WHERE 
          `dim_products`.`product_category_group_sk` =       `category_groups`.`product_category_group_sk` AND  
          `revenue_facts`.`product_sk` = `dim_products`.`product_sk`
      GROUP BY `category_groups`.`category_name`;
      

      我已经逐列索引和连接中的列。

      我的查询目前正在进行* 6分钟 * s。我想减少所花费的时间。表结构如

      表A:

      CREATE TABLE `revenue_facts` (
        `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
        `product_sk` bigint(20) unsigned NOT NULL,
        `total_price` decimal(12,2) NOT NULL,
        PRIMARY KEY (`id`),
        KEY `product_sk` (`product_sk`),
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
      

      表B:

      CREATE TABLE `dim_products` (
        `product_sk` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
        `product_category_group_sk` bigint(20) unsigned NOT NULL,
        PRIMARY KEY (`product_sk`),
        KEY `product_id` (`product_id`),
       KEY (`product_sk`) (`product_sk`)
      ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
      

      表C:

      CREATE TABLE `category_groups` (
        `product_category_group_sk` bigint(20) unsigned NOT NULL,
        `category_sk` bigint(20) unsigned NOT NULL,
        `category_name` varchar(255) NOT NULL,
        PRIMARY KEY (`product_category_group_sk`,`category_sk`),
        KEY `category_sk` (`category_sk`),
        KEY `product_category_group_sk` (`product_category_group_sk`
        KEY `category_sk` (`category_name`)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
      

      使用的执行计划是:

      1   SIMPLE  dim_products    index   PRIMARY,product_category_group_index    product_category_group_index    8   NULL    651264  Using index; Using temporary; Using filesort
      1   SIMPLE  category_groups ref PRIMARY,category_sk,product_category_group_sk,category_name product_category_group_sk   8 etl_testing.dim_products.product_category_group_sk    4   Using index
      1   SIMPLE  revenue_facts   ref product_sk  product_sk  8 etl_testing..dim_products.product_sk  5   NULL
      

1 个答案:

答案 0 :(得分:-1)

试试这个:

SELECT
    sum(`revenue_facts`.`total_price`) AS `m0`
FROM 
    (`dim_products` LEFT JOIN `category_groups` ON `dim_products`.`product_category_group_sk` =  `category_groups`.`product_category_group_sk`)
    LEFT JOIN `revenue_facts` ON `dim_products`.`product_sk` = `revenue_facts`.`product_sk`
GROUP BY `category_groups`.`category_name`;

另外,正如阿卜杜勒所说:

“发布您的表结构并解释计划”