优化 Mysql 查询

Optimise Mysql Query

我想优化下面的查询:

SELECT
                      a.id, a.pay_point_name, a.pay_point_location,
                      COUNT(b.id) AS countedCustomers,
                      SUM(b.approved) AS summedLoans,
                      SUM(c.deduction) AS summedDeductions 
                  FROM
                      pay_tbl a 
                  LEFT JOIN
                      customer_tbl b 
                          ON b.employer = a.pay_point_name 
                  LEFT JOIN
                      loans_tbl c 
                          ON c.paypoint = a.pay_point_name 
                  GROUP BY
                      a.pay_point_name 
                  ORDER BY
                      NULL

当前执行时间:161.2s

EXPLAIN 语句给出了下面的 table:

我想知道如何最好地优化此查询并减少执行时间。

假设您必须经常重复执行相同的查询。您可以使用 MySql 个视图。

https://www.mysqltutorial.org/mysql-views-tutorial.aspx

请检查我使用子查询的地方。如果这样效果更好,请使用此查询创建视图。

-- MySQL
SELECT t.id, t.pay_point_name
     , t.pay_point_location
     , COALESCE(t.countedCustomers, 0) countedCustomers
     , COALESCE(t.summedLoans, 0) summedLoans
     , COALESCE(p.summedDeductions, 0) summedDeductions
FROM (SELECT a.id, a.pay_point_name
           , MAX(a.pay_point_location) pay_point_location
           , COUNT(b.id) AS countedCustomers
           , SUM(b.approved) AS summedLoans
      FROM pay_tbl a 
      LEFT JOIN customer_tbl b 
             ON b.employer = a.pay_point_name
      GROUP BY a.id, a.pay_point_name) t
LEFT JOIN (SELECT paypoint
                , SUM(deduction) AS summedDeductions
           FROM loans_tbl
           GROUP BY paypoint) p
       ON t.pay_point_name = p.paypoint
ORDER BY t.id;