postgresql - 根据 postgres 中不同的 2 个字段选择行

标签 postgresql select distinct

我有表格消息

| 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/

相关文章:

mysql - 执行 LIKE 时忽略记录

xslt - 当 XPath 具有多个条件时,使用 XSLT 1.0 的不同值

mysql - 计算患者(女性和男性)第一次咨询的次数以及随后的咨询次数

mysql - 如何查询结果以仅显示时间戳小于给定年份的用户 ID

string - PostgreSQL 中的多个字符串替换

sql - 如果可用,从实时数据中获取温度,否则对历史数据取平均值

postgresql - 如何从 pgAdmin 4 升级中恢复

python - “模块”对象不能用 sqlalchemy 调用

sql - PostgreSQL Select where 多个 OR 语句

mysql - 在 MariaDB 中,如何从表中选择前 10 行?