1

I would like to optimise the query I have below:

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

Current Execution time: 161.2s

EXPLAIN statement gives me the table below: EXPLAIN statement gives me this table

I would like to know how best to optimise this query and reduce execution time.

Peter
  • 60
  • 8
  • Hi @Peter is there any logic for using NULL at ORDER BY clause? – Rahul Biswas Aug 09 '21 at 05:33
  • 1
    Hi @Peter Joining condition with string makes the query slower because string contains lowercase, uppercase or empty space in beginning or ending string. It is better to used integer field to better searching. Index is also efficient at integer data type instead of string data type. – Rahul Biswas Aug 09 '21 at 06:26
  • @RahulBiswas Not necessarily, I could take out the ORDER BY NULL, but it wont make any difference, do you have further recommendations? – Peter Aug 09 '21 at 09:13

2 Answers2

2

Please check this one where I've used subquery. If this works better create view with this query.

-- 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;
Rahul Biswas
  • 3,207
  • 2
  • 10
  • 20
0

Suppose if you have to repeatedly execute the same query frequently. You can use MySql views.

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

vinieth
  • 1,204
  • 3
  • 16
  • 34