mysql - MySQL查询太慢了

标签 mysql sql database performance

我试图查询一些趋势统计数据,但是基准测试非常慢。查询执行时间约为134秒。
我有一个名为table_1的mysql表。
在create语句下面

CREATE TABLE `table_1` (
  `id` bigint(11) NOT NULL AUTO_INCREMENT,
  `original_id` bigint(11) DEFAULT NULL,
  `invoice_num` bigint(11) DEFAULT NULL,
  `registration` timestamp NULL DEFAULT NULL,
  `paid_amount` decimal(10,6) DEFAULT NULL,
  `cost_amount` decimal(10,6) DEFAULT NULL,
  `profit_amount` decimal(10,6) DEFAULT NULL,
  `net_amount` decimal(10,6) DEFAULT NULL,
  `customer_id` bigint(11) DEFAULT NULL,
  `recipient_id` text,
  `cashier_name` text,
  `sales_type` text,
  `sales_status` text,
  `sales_location` text,
  `invoice_duration` text,
  `store_id` double DEFAULT NULL,
  `is_cash` int(11) DEFAULT NULL,
  `is_card` int(11) DEFAULT NULL,
  `brandid` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_registration_compound` (`id`,`registration`)
) ENGINE=InnoDB AUTO_INCREMENT=47420958 DEFAULT CHARSET=latin1;

我已经设置了一个由id+registration组成的复合索引。
在查询下面
SELECT 

store_id,
            CONCAT('[',GROUP_CONCAT(tot SEPARATOR ','),']') timeline_transactions,
            SUM(tot) AS total_transactions,
            CONCAT('[',GROUP_CONCAT(totalRevenues SEPARATOR ','),']') timeline_revenues,
            SUM(totalRevenues) AS revenues,
            CONCAT('[',GROUP_CONCAT(totalProfit SEPARATOR ','),']') timeline_profit,
            SUM(totalProfit) AS profit,
            CONCAT('[',GROUP_CONCAT(totalCost SEPARATOR ','),']') timeline_costs,
            SUM(totalCost) AS costs



 FROM (select t1.md,
COALESCE(SUM(t1.amount+t2.revenues), 0) AS totalRevenues,
COALESCE(SUM(t1.amount+t2.profit), 0) AS totalProfit,
COALESCE(SUM(t1.amount+t2.costs), 0) AS totalCost,
COALESCE(SUM(t1.amount+t2.tot), 0) AS tot,
t1.store_id

from
(
 SELECT a.store_id,b.md,b.amount from ( SELECT DISTINCT store_id FROM  table_1) AS a
  CROSS JOIN 
 (
 SELECT
  DATE_FORMAT(a.DATE, "%m") as md,
  '0' as  amount
  from (
    select curdate() - INTERVAL (a.a + (10 * b.a) + (100 * c.a)) month as Date
    from (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as a
    cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as b
    cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as c
  ) a
  where a.Date >='2019-01-01' and a.Date <= '2019-01-14'
  group by md) AS b 
)t1
left join
(
  SELECT
                COUNT(epl.invoice_num) AS tot,
                SUM(paid_amount) AS revenues,
                SUM(profit_amount) AS profit,
                SUM(cost_amount) AS costs,
                store_id,
                date_format(epl.registration, '%m') md
                FROM table_1 epl
                GROUP BY store_id, date_format(epl.registration, '%m')
)t2
ON   t2.md=t1.md AND t2.store_id=t1.store_id
group BY t1.md, t1.store_id) AS t3 GROUP BY store_id  ORDER BY total_transactions desc

在解释下面
enter image description here
enter image description here
也许我应该在registration列中从timestamp更改为datetime?

最佳答案

大约90%的执行时间将用于执行GROUP BY store_id, date_format(epl.registration, '%m')
不幸的是,您不能使用索引来group by派生值,因为这对您的报告至关重要,您需要预先计算它。您可以将该值添加到表中,例如使用生成的列:

alter table table_1 add md varchar(2) as (date_format(registration, '%m')) stored

我保留了您在本月使用的varchar格式,您也可以在本月使用数字(例如tinyint)。
这需要mysql 5.7,否则可以使用触发器来实现相同的功能:
alter table table_1 add md varchar(2) null;
create trigger tri_table_1 before insert on table_1
for each row set new.md = date_format(new.registration,'%m');
create trigger tru_table_1 before update on table_1
for each row set new.md = date_format(new.registration,'%m');

然后添加索引,最好是覆盖索引,从store_idmd开始,例如。
create index idx_table_1_storeid_md on table_1 
   (store_id, md, invoice_num, paid_amount, profit_amount, cost_amount)

如果您有其他类似的报表,您可能需要检查它们是否使用了额外的列,以及是否可以从覆盖更多列中获益。索引将需要大约1.5GB的存储空间(驱动器读取1.5GB所需的时间基本上是一手定义执行时间的,而不是缓存)。
然后将查询更改为按此新索引列分组,例如
      ...
            SUM(cost_amount) AS costs,
            store_id,
            md -- instead of date_format(epl.registration, '%m') md
            FROM table_1 epl
            GROUP BY store_id, md -- instead of date_format(epl.registration, '%m')
)t2   ...

这个索引还将处理另外9%的执行时间,SELECT DISTINCT store_id FROM table_1,这将从从store_id开始的索引中获益。
既然你的问题99%都得到了解决,接下来还有一些评论:
子查询b和您的日期范围where a.Date >='2019-01-01' and a.Date <= '2019-01-14'可能做不到您认为它做的事情。你应该分开来看它的作用。在当前状态下,它将给您一行tupleSELECT DATE_FORMAT(a.DATE, "%m") as md, ... group by md,表示“一月”,因此它基本上是一种复杂的'01', 0操作方式。除非今天是15号或更晚,否则它不会返回任何内容(这可能是无意的)。
特别是,它不会将发票日期限制在特定范围内,而是限制在任何一年的(整个)1月份的所有发票。如果这是您想要的,您应该(另外)直接添加该过滤器,例如使用select '01', 0,将执行时间减少大约12倍。所以(除了第15个和以上的问题),在你当前的范围内,你应该得到相同的结果,如果你使用
  ...
        SUM(cost_amount) AS costs,
        store_id,
        md 
        FROM table_1 epl
        WHERE md = '01'
        GROUP BY store_id, md 
)t2   ...

对于不同的日期范围,您必须调整该术语。为了强调我的观点,这与按日期过滤发票有很大的不同,例如。
  ...
        SUM(cost_amount) AS costs,
        store_id,
        md 
        FROM table_1 epl
        WHERE epl.registration >='2019-01-01' 
           and epl.registration <= '2019-01-14'
        GROUP BY store_id, md 
)t2   ...

你可能(或可能没有)尝试过。不过,在这种情况下,您需要一个不同的索引(这将是一个略有不同的问题)。
在查询的其余部分可能会有一些额外的优化、简化或美化,例如FROM table_1 epl where epl.md = '01' GROUP BY ...看起来是多余的和/或错误的(表示您实际上不在mysql 5.7上),并且group BY t1.md, t1.store_id-子查询只能为您提供1到12的值,因此生成1000个日期并再次减少它们。可以简化。但是,由于它们是在100个ish行上操作的,所以它们不会显著影响执行时间,而且我还没有详细检查它们。其中一些原因可能是由于获得了正确的输出格式或泛化(尽管,如果按其他格式而不是按月动态分组,则需要其他索引/列,但这将是另一个问题)。
另一种预先计算值的方法是使用摘要表,例如,每天运行一次内部查询(代价高昂的b),并将结果存储在表中,然后重用它(通过从该表中选择而不是执行group by)。这对于像发票这样从不更改的数据尤其可行(尽管在其他情况下,您可以使用触发器使摘要表保持最新)。如果您有几个场景,例如,如果您的用户可以决定按工作日、年、月或黄道星座分组,那么它也变得更加可行,因为否则您需要为每个场景添加一个索引。如果您需要动态限制您的发票范围(例如,2019-01-01…2019年1月14日)。如果需要在报表中包含当前日期,则仍可以预先计算,然后从表中添加当前日期的值(该值应仅包含非常有限的行数,如果索引以日期列开头,则速度很快),或者使用触发器更新随时提供汇总表。

关于mysql - MySQL查询太慢了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56139850/

相关文章:

mysql - 插入序号

Java Prepared statement Sql查询错误

SQL查找最大值然后找到其出现

sql - 从门禁表中选择先入后出时间

database - 如何在cassandra中定义动态列族

java - 我是否需要添加大量 "checks"以防止用户修改他们不应在 RESTful 应用程序中修改的数据?

ios - 从服务器更新 iOS 本地数据库

php - 如何修复从数据库填充的选择列表返回的奇数值

mysql - 非常慢的改变表(即使没有行)

PHP 错误 500 和发布数据返回空字符串