SELECT COUNT(1)
FROM
(
SELECT 1
FROM messages m1
WHERE m.to = :u
AND m.deleted_to = '0'
AND m1.unread = '1'
AND m1.from != :u
UNION ALL
SELECT 1
FROM messages m2
JOIN dialogs d1 ON m.to = -(d1.id)
JOIN dialog d2 ON d2.id = d1.id
WHERE d1.deleted = '0'
AND d1.owner = '1'
AND d2.user = :u
AND d2.deleted = '0'
AND m2.unread = '1'
AND m2.from != :u
) sel