SELECT asr.point_id, COALESCE(nullif(asr.max_cost,0),ad_set.max_cost) as max_bid, TRIM(SUBSTRING_INDEX(SUBSTRING_INDEX(st_astext(sr.pt), '(', -1), ' ', 1)) AS lat, TRIM(SUBSTRING_INDEX(SUBSTRING_INDEX(st_astext(sr.pt), ' ', -1), ')', 1)) AS lon, round(( ad_set.max_day_spend - COALESCE((select sum(cost) from ad_events where DATE(time) = CURDATE()),0) ),2) as budget_left, CASE WHEN ST_Contains(localities_poly.geom, sr.pt) THEN 1 ELSE 0 END as inside FROM ad_serv_rel asr left join serv_rel sr on asr.point_id = sr.point_id and asr.sid=sr.sid left join points p on asr.point_id = p.id left join ad_settings ad_set on ad_set.org_id = p.org_id left join ad_schedule ad_sh on ad_sh.point_id = p.id left join localities_poly on localities_poly.id = 102 WHERE ( (asr.city=1 and asr.city is not null) or st_intersects(asr.geometry, (select poly FROM localities where id=1)) ) and asr.sid = and asr.active = 1 and sr.prio > 0 and ad_set.active = 1 and ad_sh.day = CAST(MOD(DAYOFWEEK(CURDATE()) + 5, 7) + 1 AS CHAR) and CURTIME() BETWEEN ad_sh.time_start AND ad_sh.time_end