You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') AND CASE WHEN properties_loc4.name_en_loc4 IS NOT NULL THEN properties_loc4.id' at line 20
SELECT COUNT(id_prop) as total, CASE WHEN properties_loc4.name_en_loc4 IS NOT NULL THEN properties_loc4.name_en_loc4 ELSE towns.name_en_loc4 END AS town, CASE WHEN properties_loc3.name_en_loc3 IS NOT NULL THEN properties_loc3.name_en_loc3 ELSE areas1.name_en_loc3 END AS area, CASE WHEN properties_loc4.name_en_loc4 IS NOT NULL THEN properties_loc4.id_loc4 ELSE towns.id_loc4 END AS townid, CASE WHEN properties_loc3.name_en_loc3 IS NOT NULL THEN properties_loc3.id_loc3 ELSE areas1.id_loc3 END AS areaid FROM properties_loc4 towns LEFT OUTER JOIN properties_properties ON properties_properties.localidad_prop = towns.id_loc4 LEFT OUTER JOIN properties_loc3 areas1 ON towns.loc3_loc4 = areas1.id_loc3 LEFT OUTER JOIN properties_loc3 ON areas1.parent_loc3 = properties_loc3.id_loc3 LEFT OUTER JOIN properties_loc2 province1 ON areas1.loc2_loc3 = province1.id_loc2 LEFT OUTER JOIN properties_loc2 ON province1.parent_loc2 = properties_loc2.id_loc2 LEFT OUTER JOIN properties_loc1 ON province1.loc1_loc2 = properties_loc1.id_loc1 LEFT OUTER JOIN properties_loc4 ON towns.parent_loc4 = properties_loc4.id_loc4 LEFT OUTER JOIN properties_types types ON properties_properties.tipo_prop = types.id_typ LEFT OUTER JOIN properties_types ON types.parent_typ = properties_types.id_typ LEFT OUTER JOIN properties_images ON properties_properties.id_prop = properties_images.property_img AND order_img = 1 AND active_img = 1 LEFT OUTER JOIN properties_status ON properties_properties.operacion_prop = properties_status.id_sta WHERE properties_properties.activado_prop = 1 AND properties_properties.alquilado_prop = 0 AND properties_properties.vendido_prop = 0 AND CASE WHEN properties_loc4.name_en_loc4 IS NOT NULL THEN properties_loc4.loc3_loc4 ELSE towns.loc3_loc4 END IN () AND CASE WHEN properties_loc4.name_en_loc4 IS NOT NULL THEN properties_loc4.id_loc4 ELSE towns.id_loc4 END NOT IN (136) GROUP BY CASE WHEN properties_loc4.name_en_loc4 IS NOT NULL THEN properties_loc4.id_loc4 ELSE towns.id_loc4 END ORDER BY total DESC LIMIT 9