需求:有一个聊天记录表,如下
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我现在只知道h,我想查出来 每个人 和 h 聊天的最后两条记录,应该怎么写查询语句。
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我现在只知道h,我想查出来 每个人 和 h 聊天的最后两条记录,应该怎么写查询语句。
解决方案 »
- 插入有规律数据?菜鸟求助!
- linux环境下,mysql-dba常用的维护命令
- 关于auto_increment字段
- Connexion to mySQL failure : error 10060 (肯定也有人碰到过,我搞不定,SOS!)
- MYSQL数据传送时为何会出现这样的错误提示?
- RedHat Linux 7.2 下成功安装MySql后为什么不能使用?(在线守候)
- 创建表,导致mysql不作出任何提示
- 求各位大神,这种MYSQL语句是否使用强制索引?
- mysql报错
- 腾讯云ubuntu的mysql没法远程访问啊?怎么办
- 问个复合查询的问题
- Mysql:ERROR 2003 (HY000) 110错误 防火墙关闭,telnet对应端口也能通
但有个比较麻烦的方法,虽然麻烦,但思路清晰,写个proc,
cursor=select ... from group by from,to order by timeline
while()
if cursor.from 同一个from已经出现两次,就这行记录不处理,但前两条记录要保存下来。此处省略逻辑部分,只讲思路
cursor.next()
写起来难,维护也难。
X.*
FROM
TB X
WHERE
2 > (SELECT
COUNT(*)
FROM
TB
WHERE
TB.from = X.from AND TB.to = X.to
AND timeline > X.timeline)
ORDER BY X.fro , timeline;