I am using select field1, max(updated_date) from mytable.
I get the correct value for max(updated_date), i.e. the largest date.
However for field1 I just get the the value for the first record, i.e. “ta1” when I really want the “ta3” value from the third record (the one with the max date value).
e.g.
+------------+---------------------+
| field1 | update_date |
+------------+---------------------+
| ta1 | 2012-03-11 11:05:15 |
| ta2 | 2012-03-11 11:05:32 |
| ta3 | 2012-03-11 11:05:56 |
+------------+---------------------+
3 rows in set (0.00 sec)
+------------+---------------------+
| field1 | max(update_date) |
+------------+---------------------+
| ta1 | 2012-03-11 11:05:56 |
+------------+---------------------+
1 row in set (0.00 sec)
You either need a GROUP BY clause or a more complex query.
For the sample data, this will return 3 rows.
More likely, you want:
For the sample data, this will return 1 row:
Of the major DBMS, only MySQL allows you to omit the GROUP BY clause when you have a mixture of aggregates and non-aggregate columns in the select-list. The SQL standard requires the GROUP BY clause and you must list all non-aggregate columns in it. Sometimes, in MySQL, omitting the GROUP BY clause produces the answer you want; as often as not, though, it manages to give an unexpected answer.