001. Complex Query

The Query 


SELECT ctrans, cnofaktur, cno_receipt, dtanggal, ckode_customer, nsales, ndebit, nreceipt, ncredit
FROM
(SELECT 'BG' ctrans, cnofaktur, '' cno_receipt, max(dtanggal) dtanggal, ckode_customer, 0 nsales, namount ndebit, 0 nreceipt, 0 ncredit
 FROM tbl_cust_saldo 
 GROUP BY cnofaktur, ckode_customer, namount
UNION
 SELECT 'SL' ctrans, sh.cnofaktur, '' cno_receipt, sh.dtanggal, sh.ckode_customer, IFNULL(SUM((sd.ndebit*(1+(sh.ntax/100)))+sh.nfreight),0) nsales, 0 ndebit, 0 nreceipt, 0 ncredit    
 FROM tbl_sales_h sh,
      (SELECT sh.cnofaktur, IFNULL(SUM((sd.nqty*sd.nprice)-sd.ndisc),0) ndebit 
       FROM tbl_sales_h sh,
            tbl_sales_d sd
       WHERE sh.cnofaktur=sd.cnofaktur 
       GROUP BY sh.cnofaktur) sd
 WHERE sh.cnofaktur=sd.cnofaktur 
 GROUP BY sh.cnofaktur, sh.dtanggal, sh.ckode_customer
UNION
 SELECT 'RC' ctrans, rd.cnofaktur, rh.cno_receipt, rh.dtanggal, rh.ckode_from ckode_customer, 0 nsales, 0 ndebit, IFNULL(SUM(rd.ncredit-rd.ndebit),0) nreceipt, 0 ncredit 
 FROM tbl_cash_h rh,
      tbl_cash_d rd
 WHERE rh.cno_receipt=rd.cno_receipt AND
       rh.cfrom='C' 
 GROUP BY rd.cnofaktur, rh.cno_receipt, rh.dtanggal, rh.ckode_from
UNION
 SELECT 'AR' ctrans, ah.cnofaktur, '' cno_receipt, ah.dtanggal ,ah.ckode_customer, 0 nsales, 
  sum(IF(ah.ctype='D',ad.ndebit,IF(ah.ctype='C',ad.ncredit*-1,0))) ndebit, 0 nreceipt, 0 ncredit
 FROM tbl_ar_h ah, tbl_ar_d ad
 WHERE ah.cno_ar=ad.cno_ar
 GROUP BY ah.cnofaktur, ah.dtanggal, ah.ckode_customer) as inner_query
ORDER BY ckode_customer, cnofaktur, dtanggal, cno_receipt ;

EXPLAIN Output


From to above EXPLAIN output, we can see that on no 3 ...


Reference 




Comments