按指定列去重並求各值的最後一條記錄
轉自:http://wubx.net/mutli-rows-get-last-one/
在工作中經常遇到這樣的需求,一張表中某些列值是不唯一的,但是想拿到該列每個唯一記錄的最行的記錄。
這麼辦?分組?中間表?關聯查詢?還是看看下面這個簡單的方法吧。
1、創建測試表
mysql> CREATE TABLE `test` (
-> `userid` int(11) DEFAULT NULL,
-> `atime` datetime DEFAULT NULL,
-> KEY `idx_userid` (`userid`)
-> ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Query OK, 0 rows affected (0.01 sec)
2、插入測試數據
mysql> insert into test (userid,atime) values
-> (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 12:05:40'),
-> (2,'2013-08-12 12:05:43'),
-> (3,'2013-08-12 12:05:48'),
-> (5,'2013-08-12 12:06:03');
Query OK, 8 rows affected (0.00 sec)
Records: 8 Duplicates: 0 Warnings: 0
3、查看數據
mysql> select * from test ;
+--------+---------------------+
| 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 12:05:40 |
| 2 | 2013-08-12 12:05:43 |
| 3 | 2013-08-12 12:05:48 |
| 5 | 2013-08-12 12:06:03 |
+--------+---------------------+
8 rows in set (0.00 sec)
可以看到表中userid不唯一,現在要取每個userid對應的最後一條atime記錄。
給一個簡方法:
mysql> select userid,substring_index(group_concat(atime order by atime desc),",",1) as atime from test group by userid;
+--------+---------------------+
| userid | atime |
+--------+---------------------+
| 1 | 2013-08-12 12:05:40 |
| 2 | 2013-08-12 12:05:43 |
| 3 | 2013-08-12 12:05:48 |
| 5 | 2013-08-12 12:06:03 |
+--------+---------------------+
4 rows in set (0.00 sec)
4、結果分析
上面的結果是不是很神奇?
這裏巧用了substring_index字符串截取函數和group_concat字符串分組拼接函數;分步驟查看就一目瞭然了:
1)group_concat函數作用
mysql> select userid,group_concat(atime order by atime desc) as atime from test group by userid;
+--------+-----------------------------------------+
| userid | atime |
+--------+-----------------------------------------+
| 1 | 2013-08-12 12:05:40,2013-08-12 11:05:25 |
| 2 | 2013-08-12 12:05:43,2013-08-12 11:05:29 |
| 3 | 2013-08-12 12:05:48,2013-08-12 11:05:32 |
| 5 | 2013-08-12 12:06:03,2013-08-12 11:05:34 |
+--------+-----------------------------------------+
4 rows in set (0.00 sec)
2)substring_index函數作用
mysql> select userid,substring_index(group_concat(atime order by atime desc),",",1) as atime from test group by userid;
+--------+---------------------+
| userid | atime |
+--------+---------------------+
| 1 | 2013-08-12 12:05:40 |
| 2 | 2013-08-12 12:05:43 |
| 3 | 2013-08-12 12:05:48 |
| 5 | 2013-08-12 12:06:03 |
+--------+---------------------+
4 rows in set (0.00 sec)
完畢!