あなたの論理が最も早いをもたらすように見えるので、私は少し混乱しています 最新のものではないメッセージ。
distinct on
非常に強力です。あなたが欲しいものをすぐに手に入れることができるかどうかはわかりません。私の傾向は、ウィンドウ関数の使用に切り替えることです:
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;