首页 > 解决方案 > 从 2 列中获取最后一个不同的值

问题描述

我想要一些有关此代码的帮助。我正在尝试在 MySQL 中选择最后一条聊天消息。这是我的桌子:

ID id_user_to id_user_from 信息 时间戳
1 1 2 你好 1633345082
2 2 1 你好 1633345083
3 1 3 其他 1633345088
4 3 1 另一个2 1633345088

如果我要选择用户 1 的最后一条消息,我会得到第二行,因为它具有最新的时间戳。我能怎么做?我尝试了这段代码,但我不知道如何使其适应我的上下文,因为我必须检查用户是否在from_user_idorto_user_id列中被占用一次,并且始终使用最新的时间戳。

SELECT * 
FROM [tableName] 
WHERE id IN (
  SELECT MAX(id)
  FROM [tableName]
  GROUP BY code
)

标签: mysqlsql

解决方案


如果您希望特定用户发送或接收的最后一条消息:

select * from [tableName] 
where id_user_to = 1 or id_user_from = 1
order by timestamp desc limit 1

好的,你的第二个问题:

select * from (
select *, row_number() over (partition by user1,user2 order by timestamp desc) rn 
from (
   select id ,id_user_to user1,id_user_from user2,message,timestamp
   from table where id_user_to =1
   union all
   select id ,id_user_from, id_user_to,message,timestamp
   from table  where id_user_from =1
) t ) t where rn = 1

如果您在子查询中删除用户 ID 的条件,您将获得所有用户 ID 的最新消息


推荐阅读