SELECT DISTINCT p.id, p.ref_n as ref, p.type_id, p.deal_type, p.top_offer_id,
			  pt.short_descr, p.bedrooms, p.bathrooms, p.price as price_text, pt.slug,
			  pi.image,
			  t.name as type,t.slug as tslug,
			  st.name as stype,st.slug as stslug,
			  r.slug as rslug, r.name as region,
			  sr.slug as srslug, sr.name as sregion
		FROM premises p 
		INNER JOIN premises_text pt ON p.id = premise_id AND pt.language_id = 1
		LEFT JOIN ( SELECT image, page_id FROM premises_images ORDER BY main ) pi ON p.id = pi.page_id
		LEFT JOIN pages_text t ON t.page_id = p.type_id AND t.language_id = 1
		LEFT JOIN pages_text st ON st.page_id = p.subtype_id AND st.language_id = 1
		LEFT JOIN pages_text r ON r.page_id = p.region_id AND r.language_id = 1
		LEFT JOIN pages_text sr ON sr.page_id = p.subregion_id AND sr.language_id = 1
		WHERE 
		p.status != 'deleted'
		AND ref_n > 
		GROUP BY p.id
		ORDER BY cast(ref_n as unsigned) ASC LIMIT 1;
		

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'GROUP BY p.id
		ORDER BY cast(ref_n as unsigned) ASC LIMIT 1' at line 18

file -
line -