Estoy un poco confundido, porque su lógica parecería traer el primero El mensaje no es el último.
Aunque distinct on
es bastante poderoso, no estoy seguro de si puede obtener fácilmente lo que desea. Mi inclinación es cambiar al uso de funciones de ventana:
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;