select deb.id , mc.cid , mc.mail_month from fte_intra.debiteuren deb left join gmsms.mail_count mc on (mc.cid = deb.id) where deb.type='sms' AND (deb.Afloop_contract='0000-00-00' OR month(deb.Afloop_contract)='$lastmonth') AND mc.month='$lastmonth' AND mc.year='$yearG' group by deb.id order by deb.id