Saya agak bingung, karena logika Anda akan muncul untuk membawa paling awal pesan bukan yang terbaru.
Meskipun distinct on
cukup kuat, saya tidak yakin apakah Anda dapat dengan mudah mendapatkan apa yang Anda inginkan. Kecenderungan saya adalah beralih menggunakan fungsi jendela:
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;