Ik ben een beetje in de war, omdat jouw logica de vroegste . lijkt te brengen bericht niet de laatste.
Hoewel distinct on
is vrij krachtig, ik weet niet zeker of je gemakkelijk kunt krijgen wat je wilt. Mijn neiging is om over te schakelen naar het gebruik van vensterfuncties:
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;