请教个mysql查询语句
假如现在有个数据库表,列有rowid,user,score,testtime.不同user的多个score按testtime已经插入在这表格。请问怎么找出每个user最近两次的score和对应的testtime。谢谢!
[解决办法]
参考下贴中的多种方法
http://blog.csdn.net/acmain_chm/article/details/4126306
[征集]分组取最大N条记录方法征集,及散分....
[解决办法]
- SQL code
root@localhost : test 02:18:41>select * from us;+-------+------+-------+---------------------+| rowid | user | score | testtime |+-------+------+-------+---------------------+| 1 | a | 80 | 2012-09-03 14:11:31 || 2 | a | 60 | 2012-09-03 14:11:53 || 3 | a | 75 | 2012-09-03 14:11:57 || 4 | b | 59 | 2012-09-03 14:12:14 || 5 | b | 69 | 2012-09-03 14:12:22 || 6 | b | 79 | 2012-09-03 14:12:42 || 7 | c | 90 | 2012-09-03 14:12:57 || 8 | c | 95 | 2012-09-03 14:13:04 || 9 | d | 85 | 2012-09-03 14:13:13 |+-------+------+-------+---------------------+9 rows in set (0.00 sec)root@localhost : test 02:18:46>select a.* from us a where 2>(select count(*) from us b where a.user=b.user and b.testtime > a.testtime );+-------+------+-------+---------------------+| rowid | user | score | testtime |+-------+------+-------+---------------------+| 2 | a | 60 | 2012-09-03 14:11:53 || 3 | a | 75 | 2012-09-03 14:11:57 || 5 | b | 69 | 2012-09-03 14:12:22 || 6 | b | 79 | 2012-09-03 14:12:42 || 7 | c | 90 | 2012-09-03 14:12:57 || 8 | c | 95 | 2012-09-03 14:13:04 || 9 | d | 85 | 2012-09-03 14:13:13 |+-------+------+-------+---------------------+
[解决办法]
分组取前两条吧
- SQL code
SELECT a.rowid,a.user,a.score,a.testtime FROM score_us a LEFT JOIN score_us b ON a.user = b.user AND a.testtime < b.testtime GROUP BY a.rowid,a.user,a.score,a.testtime HAVING COUNT(b.rowid) < 2 ORDER BY a.testtime
[解决办法]
root@localhost : test 02:18:46>select a.* from us a where 2>(select count(*) from us b where a.user=b.user and b.testtime > a.testtime );
+
这个可以