獲取MySQL的表中每個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;
數(shù)據(jù)如下:
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對應的時間離現(xiàn)在最近的一條記錄.初看到一個這條件一般都會想到借用臨時表及添加主建借助于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!
相關(guān)文章
MySQL數(shù)據(jù)庫優(yōu)化之分表分庫操作實例詳解
這篇文章主要介紹了MySQL數(shù)據(jù)庫優(yōu)化之分表分庫操作,結(jié)合實例形式詳細分析了mysql數(shù)據(jù)庫分表分庫垂直拆分、水平拆分相關(guān)原理以及應用案例,需要的朋友可以參考下2020-01-01SQL中from_unixtime函數(shù)的使用方法實例
在MySQL數(shù)據(jù)表設計中,時間字段一般都設計為時間戳格式的,開發(fā)人員去查看的時候就顯得有點不方便,可以使用FROM_UNIXTIME轉(zhuǎn)換成日期格式進行查看,下面這篇文章主要給大家介紹了關(guān)于SQL中from_unixtime函數(shù)的使用方法的相關(guān)資料,需要的朋友可以參考下2022-08-08SQL的substring_index()用法實例(MySQL字符串截取)
substring_index?(字符串,分隔符,序號),主要作用是用于截取目標字符串,下面這篇文章主要給大家介紹了關(guān)于SQL中substring_index()用法(MySQL字符串截取)的相關(guān)資料,需要的朋友可以參考下2023-01-01MySQL如何導入csv格式數(shù)據(jù)文件解決方案
本文將詳細介紹MySQL如何導入csv格式數(shù)據(jù)文件并提供詳細解決方案,需要了解的朋友可以參考下2012-11-11用SQL語句解決mysql導入大數(shù)據(jù)文件的問題
今天的這篇文章用來討論如何解決導入mysql大數(shù)據(jù)文件的問題,其實說的簡單了就是一條SQL語句,而如果你是一名SQL高手,那完全可以略過此文。2010-08-08Mysql快速插入千萬條數(shù)據(jù)的實戰(zhàn)教程
這篇文章主要給大家介紹了關(guān)于Mysql快速插入千萬條數(shù)據(jù)的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-03-03