select O.id as order_id,O.street_num,O.pre_dir,O.post_dir,O.address1,O.address2,O.suffix,O.state,O.city, C.county,S.status_date, L.name as lending_company,B.name as lending_branch,B.id as branch_id,LO.id as lo_id,LO.first_name as lo_first_name, LO.last_name as lo_last_name,P.name as payment_type,E.id as event_id,E.event_time from orders as O left join events as E on (E.id=O.event_id) left join companies as L on (O.lending_company=L.id) left join branches as B on (O.lending_branch=B.id) left join users as LO on (O.loan_officer=LO.id) left join payment_types as P on (O.payment_type=P.id) left join counties as C on (C.id=O.county) left join status_states as S on (S.order_id=O.id and S.status_state='24') where O.id in (select distinct order_id from charges where '$d1' <= input_date and input_date <= '$d2' union select distinct order_id from events where '$d1' <= event_time and event_time <= '$d2' union select distinct order_id from status_states where '$d1' <= status_date and status_date <= '$d2') and E.id=O.event_id order by O.id