I have a MySQL (5.1.49) table with three columns.
mysql> create table testme(id int auto_increment, id2 int not null, somedate datetime, primary key(id));
In my case id2 is not unique, but I want to return rows with distinct id2 values with the max somedate.
Here’s some sample data.
mysql> insert into testme values (1, 5, '2012-01-02 01:01:01'),(2, 5, '2012-02-02 02:02:02'),(3, 7, '2010-01-10 11:01:33');
This question almost answers mine, but with the extra id field, the returned id and id2 don’t match. For id2=5, it’s returning id=1 instead of id=2.
mysql> select id, id2, max(somedate) from testme group by id2;
+----+-----+---------------------+
| id | id2 | max(somedate) |
+----+-----+---------------------+
| 1 | 5 | 2012-02-02 02:02:02 |
| 3 | 7 | 2010-01-10 11:01:33 |
+----+-----+---------------------+
I’m expecting,
+----+-----+---------------------+
| id | id2 | max(somedate) |
+----+-----+---------------------+
| 2 | 5 | 2012-02-02 02:02:02 |
| 3 | 7 | 2010-01-10 11:01:33 |
+----+-----+---------------------+
Want the ID that matches maximum date for each ID2
Does anyone have any ideas please? Thanks
This query would definitely work, although it may be not the optimal one: