使用左连接优化查询

时间:2014-01-17 07:15:35

标签: mysql performance

以下查询正在执行~30秒。我找不到瓶颈。请帮我提高性能。

SELECT 'Beginning Balance' AS TYPE, 
       COUNT(DISTINCT lmt.lmt_corp_id) ,
       COUNT(DISTINCT ldt.ldt_clnt_id) ,
       COUNT(DISTINCT ldt.ldt_guar_id) ,
       COUNT(DISTINCT ldt.ldt_loan_ref_id),
       COUNT(ldt.ldt_line_item_id) ,
       SUM(ldt.ldt_princpal_bal) , 
       SUM(ldt.ldt_fund_amt), 
       SUM(ldt.ldt_princpal_bal) - SUM(ldt.ldt_fund_amt), 
       SUM(pay.PaidPrinc), 
       SUM(pay.PaidInt), 
       SUM(pay.PaidOther), 
       SUM(pay.TotalPmt), 
       SUM(fn_get_line_pb_by_date(ldt.ldt_line_item_id, '2014-01-16', 'BOD')), 
       sum(ovr.OPAmt),
FROM ldt_tran_loan_det ldt
JOIN lmt_mst_loan lmt 
  ON ldt.ldt_loan_ref_id = lmt.lmt_loan_id AND 
     ldt.ldt_clnt_id IN (262,75,191,49,267,277,23,79)
LEFT JOIN tmp_pmt pay ON pay.LineItemId = ldt.ldt_line_item_id
LEFT JOIN tmp_over_pmt ovr ON ovr.LineItemId = ldt.ldt_line_item_id   
LEFT JOIN lct_tran_loan_close lct 
       ON lct.lct_line_item_id = ldt.ldt_line_item_id
WHERE DATE(ldt.ldt_funded_date) < '2014-01-16' AND 
      (ldt.ldt_status != 'PIF' OR 
       (ldt.ldt_status = 'PIF' AND ldt.ldt_last_pmt_date >= '2014-01-16')) AND
      (lct.lct_hff_entry_date IS NULL OR 
       (DATE(lct.lct_hff_entry_date) >= '2014-01-16' AND 
        lct.lct_txn_type IN ('REC','RCL')))

DDL:

CREATE TABLE `ldt_tran_loan_det` 
( `ldt_line_item_id` bigint(20),
  `ldt_loan_ref_id` int(11) ,
  `ldt_clnt_id` int(11) ,
  `ldt_guar_id` int(11) ,
  `ldt_princpal_bal` decimal(20,2) ,
  `ldt_fund_amt` decimal(20,2) ,
  `ldt_funded_date` datetime ,
  `ldt_last_pmt_date` date , 
  PRIMARY KEY (`ldt_line_item_id`));

CREATE TABLE `lmt_mst_loan` (`lmt_loan_id` int(11), `lmt_corp_id` int(11) );

CREATE TABLE `tmp_pmt` 
(`PaidPrinc` decimal(20,2),
 `PaidInt` decimal(20,2),
 `PaidOther` decimal(20,2),
 `TotalPmt` decimal(20,2),
 `LineItemId` int(11));

CREATE TABLE `tmp_over_pmt` ( `OPAmt` decimal(20,2),`LineItemId` int(11) );

CREATE TABLE `lct_tran_loan_close` 
(`lct_line_item_id` bigint(20),
 `lct_txn_type`char(20) , 
 `lct_hff_entry_date` datetime);

这是执行计划: enter image description here

1 个答案:

答案 0 :(得分:2)

这不是最终解决方案,只是一个改进点:
在ldt_funded_date列上创建索引。不要使用date()函数,因为它不会使用索引。而是使用ldt.ldt_funded_date&lt; '2014-01-16 00:00:00'