mysql最后一条记录id_获取MySQL的表中每个userid最后一条记录的方法

本文介绍了一种在MySQL中获取每个`userid`对应最新`atime`记录的简便方法,无需借助临时表和主键。通过`GROUP_CONCAT`结合`SUBSTRING_INDEX`函数,按`atime`降序排列后取第一个值,即可得到每个用户的最近活动时间。
摘要由CSDN通过智能技术生成

如下表:

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的表中每个userid最后一条记录的方法

本文地址: http://www.cppcns.com/shujuku/mysql/124396.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值