SELECT `a`.*, IFNULL((SELECT DISTINCT referenceNo from view_journal_table where formNo = a.formNo and companyID = a.companyID LIMIT 0, 1), "---") as refNo, concat((SELECT sam2.acctName FROM comp_journal_detail sam1
 JOIN comp_chart_of_acct sam2 on sam2.ID = sam1.acctCode
 WHERE sam1.companyID = a.companyID 
 and sam1.journalID = a.journalID 
 and sam1.sequence = IF(a.sequence%2 = 0, a.sequence-1, a.sequence+1)), ' - ', SUBSTR(a.description, 1, 20)) AS description, `b`.`effective_date`
FROM (`comp_journal_detail` a)
JOIN `comp_journal` b ON `b`.`journalID` = `a`.`journalID` and b.companyID = a.companyID and b.status = 1
WHERE `a`.`companyID` =  '3'
AND `a`.`acctCode` =  '32507'
AND `a`.`year` =  '2015'
AND `a`.`period` != 0
AND CONCAT(b.year,LPAD(b.period,2,"0")) <= '201512'
ORDER BY `b`.`effective_date`, `journalID`, `sequence`