mysql group by和max [重复]

Posted

技术标签:

【中文标题】mysql group by和max [重复]【英文标题】:mysql group by and max [duplicate] 【发布时间】:2018-06-29 04:31:24 【问题描述】:

我在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)

如何更改脚本以在我的服务器版本上运行? 谢谢!

【问题讨论】:

【参考方案1】:

您可以申请自加入;

select t1.* from table1 t1 inner join 
(select code,max(date) maxDate from table1 group by code) t2
ON t1.code = t2.code and t1.date = t2.maxDate

Demo

【讨论】:

【参考方案2】:

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 group by和max [重复]的主要内容,如果未能解决你的问题,请参考以下文章

使用 MAX() 和 GROUP BY 没有返回正确的结果[重复]

COUNT MAX CASE 和 GROUP BY 用于重复类型 id

将 Max() 与 GROUP BY 的其他字段一起使用 [重复]

MySQL GROUP BY 和 SELECT GROUP BY [重复]

GROUP BY with MAX(DATE) [重复]

GROUP BY 和 mysql 5.7 [重复]