zoukankan      html  css  js  c++  java
  • 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; 
    

    表数据:

    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) 
    
  • 相关阅读:
    CSU 1333 Funny Car Racing
    FZU 2195 检查站点
    FZU 2193 So Hard
    ZOJ 1655 FZU 1125 Transport Goods
    zoj 2750 Idiomatic Phrases Game
    hdu 1874 畅通工程续
    hdu 2489 Minimal Ratio Tree
    hdu 3398 String
    洛谷 P2158 [SDOI2008]仪仗队 解题报告
    POJ 1958 Strange Towers of Hanoi 解题报告
  • 原文地址:https://www.cnblogs.com/mslagee/p/5578601.html
Copyright © 2011-2022 走看看