Je suis un peu confus, car votre logique semblerait apporter le plus tôt message pas le dernier.
Bien que distinct on
est assez puissant, je ne sais pas si vous pouvez facilement obtenir ce que vous voulez. J'ai tendance à passer à l'utilisation des fonctions de fenêtre :
SELECT m.*
FROM (SELECT m.*,
(CASE WHEN sender_id < recipient_id
THEN (sender_id, recipient_id)
ELSE (recipient_id, sender_id)
END) AS pair,
ROW_NUMBER() OVER (PARTITION BY (CASE WHEN sender_id < recipient_id
THEN (sender_id, recipient_id)
ELSE (recipient_id, sender_id)
END)
ORDER BY created_at, unread_count DESC
) as seqnum,
SUM(CASE WHEN m.opened = false THEN 0 ELSE 1 END) OVER
(PARTITION BY (CASE WHEN sender_id < recipient_id
THEN (sender_id, recipient_id)
ELSE (recipient_id, sender_id)
END)
) as NumUnopened
FROM "messages" m
WHERE ((recipient_id = 6 and recipient_delete = false) or
(sender_id = 6 and sender_delete = false))
) t
WHERE seqnum = 1;