有一个聊天记录表,如下
id from to message timeline
1 a h xxxxxxxx 10:24:35
2 c h xxxxxxxx 10:26:20
3 h a xxxxxxxx 10:30:56
4 c h xxxxxxxx 10:32:27
5 a h xxxxxxxx 10:35:25
6 h c xxxxxxxx 10:42:45
7 h b xxxxxxxx 10:45:32
现在要查询出最新的聊天记录,两个人之间互发的,只取一条。比如c和h之间的,只取
6 h c xxxxxxxx 10:42:45
SQL语句该如何来写呢?
方案推荐指数:10
找出H与C聊天的最新纪录:
select * from tbl
where ( (from = “”H”” and to = “”C””) or (from = “”C”” and to = “”H””))
order by timeline desc limit 0,1
select * from tbl
where ( (from = “”H”” and to = “”C””) or (from = “”C”” and to = “”H””))
order by timeline desc limit 0,1
方案推荐指数:10
如果时间不会重复
select * from a1 where timeline in (
select max(timeline) from a1 group by concat(if(`from` < `to`, `from`, `to`), if(`from` > `to`, `from`, `to`)))