从消息表中获取不同的最近联系人列

093gszye  于 2021-07-29  发布在  Java
关注(0)|答案(1)|浏览(266)

我有一个消息表,我想从中获取“user1”的最新联系人,现在该表如下所示:

我能得到的最接近的sql查询是

SELECT receiver, sender, time 
from message 
where receiver = 'user1' OR sender = 'user1' 
group by receiver, sender ORDER by time desc

它回来了

但它应该返回只包含不同的“user2”、“host1”的结果,但该行重复了两次

f4t66c6m

f4t66c6m1#

正如@akina所建议的,通过此查询获得的预期结果:

SELECT CASE WHEN receiver = 'user1' THEN sender ELSE receiver END AS contact, max(time) AS time 
FROM message 
WHERE receiver = 'user1' OR sender = 'user1' 
GROUP BY CASE WHEN receiver = 'user1' THEN sender ELSE receiver END

它回来了

相关问题