获取MySQL的表中每个userid最后一条记录的方法
程序员文章站
2024-02-28 10:26:34
如下表:
create table `t1` (
`userid` int(11) default null,
`atime` datetime defa...
如下表:
create table `t1` ( `userid` int(11) default null, `atime` datetime default null, key `idx_userid` (`userid`) ) engine=innodb default charset=utf8; create table `t1` ( `userid` int(11) default null, `atime` datetime default null, key `idx_userid` (`userid`) ) engine=innodb default charset=utf8;
数据如下:
mysql> select * from t1; +--------+---------------------+ | userid | atime | +--------+---------------------+ | 1 | 2013-08-12 11:05:25 | | 2 | 2013-08-12 11:05:29 | | 3 | 2013-08-12 11:05:32 | | 5 | 2013-08-12 11:05:34 | | 1 | 2013-08-12 11:05:40 | | 2 | 2013-08-12 11:05:43 | | 3 | 2013-08-12 11:05:48 | | 5 | 2013-08-12 11:06:03 | +--------+---------------------+ 8 rows in set (0.00 sec) mysql> select * from t1; +--------+---------------------+ | userid | atime | +--------+---------------------+ | 1 | 2013-08-12 11:05:25 | | 2 | 2013-08-12 11:05:29 | | 3 | 2013-08-12 11:05:32 | | 5 | 2013-08-12 11:05:34 | | 1 | 2013-08-12 11:05:40 | | 2 | 2013-08-12 11:05:43 | | 3 | 2013-08-12 11:05:48 | | 5 | 2013-08-12 11:06:03 | +--------+---------------------+ 8 rows in set (0.00 sec)
其中userid不唯一,要求取表中每个userid对应的时间离现在最近的一条记录.初看到一个这条件一般都会想到借用临时表及添加主建借助于join操作之类的.
给一个简方法:
mysql> select userid,substring_index(group_concat(atime order by atime desc),",",1) as atime from t1 group by userid; +--------+---------------------+ | userid | atime | +--------+---------------------+ | 1 | 2013-08-12 11:05:40 | | 2 | 2013-08-12 11:05:43 | | 3 | 2013-08-12 11:05:48 | | 5 | 2013-08-12 11:06:03 | +--------+---------------------+ 4 rows in set (0.03 sec) mysql> select userid,substring_index(group_concat(atime order by atime desc),",",1) as atime from t1 group by userid; +--------+---------------------+ | userid | atime | +--------+---------------------+ | 1 | 2013-08-12 11:05:40 | | 2 | 2013-08-12 11:05:43 | | 3 | 2013-08-12 11:05:48 | | 5 | 2013-08-12 11:06:03 | +--------+---------------------+ 4 rows in set (0.03 sec)
good luck!
推荐阅读
-
Mysql中 show table status 获取表信息的方法
-
Mysql中 show table status 获取表信息的方法
-
清理8组nodes中表的历史数据,平均每个node中的表有1.5亿条记录_MySQL
-
PHP+MySQL统计该库中每个表的记录数并按递减顺序排列的方法,mysql记录数_PHP教程
-
SQL获取第一条记录的方法(sqlserver、oracle、mysql数据库)
-
ThinkPHP模板中判断volist循环的最后一条记录的验证方法_PHP
-
Mysql获取id最大值、表的记录总数等相关问题的方法汇总
-
Java获取最后插入MySQL记录的自增ID值的3种方法
-
Mysql获取id最大值、表的记录总数等相关问题的方法汇总
-
Java获取最后插入MySQL记录的自增ID值的3种方法