从两列中获取最后一个不同的值



我想要一些帮助与这个代码。我试图选择MySQL的最后一个聊天消息。这是我的表格:

<表类> id id_user_to id_user_from 消息 时间戳 tbody><<tr>112嗨1633345082221你好1633345083313另一个1633345088431Another21633345088

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

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
如果您在子查询中删除userid上的条件,您将获得所有用户id的最新消息

最新更新