我有一个包含表 MESSAGE 的数据库,它包含我的所有消息。 我需要找到所有最后的对话消息。
该表包含以下字段: 身份证号(整数) 来自(整数) 至(整数) 日期(日期) 消息(varchar)
我需要找到一个查询,该查询可以返回所有最后的消息。 例如:
1 -> 3 : This is a first message; yesterday
3 -> 1 : This is the last one; today
1 -> 2 : Another message with 1 and 2; some time
3 -> 5 : Some message i don't need; some time
我需要找到:
"3 -> 1 : This is the last one; today"
"1 -> 2 : Another message with 1 and 2; some time"
我希望我的意思很清楚...... 我已经可以通过以下查询找到与我对话的用户:
在此示例中,用户的 Id = 47
select distinct m.To from MESSAGE m Where m.From = 47 union select distinct m2.from From MESSAGE m2 where m2.To = 47
谢谢!
最佳答案
我认为这会做你想要的,假设 id 可以用来定义“最后一条消息”:
select m.*
from message m join
(select least(from, to) as p1, greatest(from, to) as p2, max(id) as maxid
from message m
group by least(from, to), greatest(from, to)
) mmax
on m.id = mmax.maxid
这使用 id 来查找对话中的最后一条记录。然后它会返回以获取消息。
关于mysql - SQL嵌套查询问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12748256/