1

我想优化下面的查询:

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 语句给了我下表: EXPLAIN 语句给了我这张表

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

4

2 回答 2

1

请检查我使用子查询的这个。如果这更有效,则使用此查询创建视图。

-- 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;
于 2021-08-09T09:27:25.867 回答
0

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

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

于 2021-08-09T06:08:30.577 回答