我想要一些帮助与这个代码。我试图选择MySQL的最后一个聊天消息。这是我的表格:
<表类>
id
id_user_to
id_user_from
消息
时间戳
tbody><<tr>1 1 2 嗨 1633345082 22 1 你好 1633345083 3 1 3 另一个 1633345088 43 1 Another2 1633345088 表类>
如果您想要特定用户发送或接收的最后一条消息:
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的最新消息