我有表格消息
| 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 的用户,想要选择我所在的行是 user_id 或 recepient_id(但每个 user_id/recepient_id 对只有 1 行)。在这个例子中,我想选择带有 id 的消息 - 2、4(或 1、4 或 2、3 或 2、4。没关系。只需为 user_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
关于postgresql - 根据 postgres 中不同的 2 个字段选择行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11147708/