mysql - 从 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_id
orto_user_id
列中被占用一次,并且始终使用最新的时间戳。
SELECT *
FROM [tableName]
WHERE id IN (
SELECT MAX(id)
FROM [tableName]
GROUP BY code
)
解决方案
如果您希望特定用户发送或接收的最后一条消息:
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 的最新消息
推荐阅读
- sql - INNER JOIN 与两个具有相同字段的相同表
- wpf - WPF 图像周围奇怪的黑色背景
- reactjs - Reactjs:如何在单击按钮时一次显示一个切换的内容
- javascript - 期望一个字符串(用于内置组件)或一个类/函数(用于复合组件)但得到:对象
- javascript - 当“循环”为真时,无法通过其标签切换复选框
- django - TypeError:__init__() 为 reportlab django 获得了一个意外的关键字参数“as_attachment”
- javascript - readable.destroy() 不会同时发出“关闭”和“错误”事件 Node.js
- sql-server - MSSQL将名称解析为两个新列并添加到同一个表中
- json - 如何解析 .jsx 文件中的外部 JSON 文件
- keras - 计算 Keras 中的神经元(具有不同的层),我的方法正确吗?