SELECT * FROM
(
SELECT t.*, c.user_profile_id, c.user_profile_avatar, c.user_profile_realname
FROM messages t
JOIN dev_users_profile c
ON t.message_target = c.user_profile_id
OR t.message_author = c.user_profile_id
WHERE (t.message_author=?i AND c.user_profile_id!=?i)
OR (t.message_target=?i AND c.user_profile_id!=?i)
ORDER BY t.message_date DESC
) AS temp
GROUP BY user_profile_id
ORDER BY message_date DESC