发布于 2016-03-30 04:58:38 | 158 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的Mysql教程,程序狗速度看过来!

Mysql关系型数据库管理系统

MySQL是一个开放源码的小型关联式数据库管理系统,开发者为瑞典MySQL AB公司。MySQL被广泛地应用在Internet上的中小型网站中。由于其体积小、速度快、总体拥有成本低,尤其是开放源码这一特点,许多中小型网站为了降低网站总体拥有成本而选择了MySQL作为网站数据库。


这篇文章主要介绍了获取MySQL的表中每个userid最后一条记录的方法,并且针对userid不唯一的情况,需要的朋友可以参考下

如下表:


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!



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务