Postgresql error: column must appear in the GROUP BY clause or be used in an aggregate function

Postgresql error: column must appear in the GROUP BY clause or be used in an aggregate function

从我想获取 'user1' 最近联系人的消息 table,现在 table 看起来像这样:

| id | receiver | sender | time       |
|----|----------|--------|------------|
| 1  | user1    | host1  | 2020-07-02 |
| 2  | host2    | user1  | 2020-07-03 |
| 3  | user3    | host3  | 2020-07-04 |

我设法通过使用 mysql:

获得了预期的结果
SELECT CASE WHEN receiver = 'user1' THEN sender ELSE receiver END AS id, max(time) AS time 
FROM message WHERE receiver = 'user1' OR sender = 'user1' 
GROUP BY CASE WHEN receiver = 'user1' THEN sender ELSE receiver END;

但是当我 运行 在 postgres 上进行此查询时,我收到错误:Postgresql 错误:列接收者必须出现在 GROUP BY 子句中或用于聚合函数中。有解决此问题的解决方案吗?

我建议 distinct on:

select distinct on ( case when receiver = 'user1' then sender else receiver end ) m.*
from messages m
where 'user1' in (receiver, sender)
order by (case when receiver = 'user1' then sender else receiver end), time desc;