我有桌子留言
| id | user_id | recepient_id | message
| 1 | 1 | 2 | test1
| 2 | 1 | 2 | test2
| 3 | 2 | 1 | test3
| 4 | 3 | 1 | test4
| 5 | 3 | 2 | test5
我是id为1的用户,希望选择行,其中我是用户id或recepient id(但每个用户id/recepient id对只有一行)。在这个例子中,我想选择id为-2、4(或1、4或2、3或2、4)的消息。没关系。只需获取用户id/recepient id的uniq对)
我该怎么做?
最佳答案
select distinct on (least(user_id, recipient_id), greatest(user_id, recipient_id))
id, user_id, recipient_id, message
from the_table
where user_id = 1 or recipient_id = 1