2

I have this table in 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   |
+----+------+------------+-------+

I want to return a table like this:

+------+------------+-------+
| code |    date    | value |
+------+------------+-------+
|  3   | 2016-06-06 |   5   |
|  8   | 2016-09-09 |   3   |
+------+------------+-------+

My server setings is:

**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 $

I tried this script and not work:

SELECT *
FROM tbl_mysql
WHERE date IN (SELECT MAX(date) FROM tbl_mysql GROUP BY code)

How can I change the script to work on my server version? Thank you!

Bill Karwin
  • 538,548
  • 86
  • 673
  • 828
Hexman
  • 327
  • 1
  • 11

2 Answers2

2

You can apply self join;

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

lucky
  • 12,734
  • 4
  • 24
  • 46
1

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
Alex
  • 16,739
  • 1
  • 28
  • 51