Query has wrong grouping and is a bit too complicated. It's enough to return only count (and use loadResult):

    SELECT COUNT(*) FROM {$db->quoteName('#__kunena_attachments')} AS a INNER JOIN {$db->quoteName('#__kunena_messages')} AS m ON a.mesid=m.id WHERE m.thread={$topicid}