SELECT content.id as content_id,content.container_id as category_id, content.html_name as content_html_name, content_still.id as still_id, content_still.still_type as still_type, content_still.container_id as page_id, content_still.name as still_name, content_still.title as still_title, content_still.description as still_description, content_still.keywords as still_keywords, content_still.html_name as still_html_name, content_still.sort_order as sort_order, content_still_rooms.id as room_id, content_still_gallery.id as pic_id, content_still_gallery.thumbnail as thumbnail FROM content JOIN content_still ON content.id=content_still.container_id JOIN content_still_rooms ON content_still.id=content_still_rooms.still_id JOIN content_still_gallery ON content_still_rooms.id=content_still_gallery.still_id WHERE content.id = $id AND HAVING MIN(content_still_rooms.sort_order) AND content_still_gallery.thumbnail IS NOT NULL AND content_still_gallery.sort_order=5 GROUP BY content,content_still,content_still_gallery,content_still_gallery.id as pic_id, content_still_gallery.thumbnail as thumbnail ORDER BY content_still_rooms.sort_orderYou have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'HAVING MIN(content_still_rooms.sort_order) AND content_still_gallery.thumbnail I' at line 9