獲得MySQL的表中每一個userid最初一筆記錄的辦法。本站提示廣大學習愛好者:(獲得MySQL的表中每一個userid最初一筆記錄的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是獲得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;
數據以下:
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!