This question already has answers here:
Retrieving the last record in each group - MySQL
(25个答案)
去年关门了。
我在mysql中有这个表:
+----+------+------------+-------+
| id | code |    date    | value |
+----+------+------------+-------+
| 1  |   3  | 2016-01-01 |   3   |
| 2  |   3  | 2016-01-02 |   4   |
| 3  |   3  | 2016-03-01 |   6   |
| 4  |   3  | 2016-06-06 |   5   |
| 5  |   8  | 2016-01-01 |   1   |
| 6  |   8  | 2016-09-09 |   3   |
+----+------+------------+-------+

我想退一张这样的桌子:
+------+------------+-------+
| code |    date    | value |
+------+------------+-------+
|  3   | 2016-06-06 |   5   |
|  8   | 2016-09-09 |   3   |
+------+------------+-------+

我的服务器设置是:
**MySQL**
Server: localhost via TCP/IP
Server version: 5.5.16
Protocol version: 10
User: root@localhost
MySQL charset: UTF-8 Unicode (utf8)

**Web server**
Apache/2.2.21 (Win32) mod_ssl/2.2.21 OpenSSL/1.0.0e PHP/5.3.8
MySQL client version: mysqlnd 5.0.8-dev - 20102224 - $Revision: 310735 $

我试过这个剧本但没成功:
SELECT *
FROM tbl_mysql
WHERE date IN (SELECT MAX(date) FROM tbl_mysql GROUP BY code)

如何更改脚本以在服务器版本上工作?
谢谢您!

最佳答案

http://sqlfiddle.com/#!9/4cf933/2

SELECT t.*
FROM tbl_mysql t
LEFT JOIN tbl_mysql t2
ON t.code = t2.code
   AND t.date<t2.date
WHERE t2.id IS NULL

关于mysql - mysql group by and max ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48349466/

10-12 12:52
查看更多