I have a table in MySql with the following data, where id_pers
is a foreign key to another table people.
--------------------------------------------
id | id_pers | created_at |
--------------------------------------------
1 | 1 | 2016-09-12 16:59:11 |
--------------------------------------------
2 | 1 | 2016-09-12 17:03:45 |
--------------------------------------------
3 | 1 | 2016-09-12 17:03:30 |
--------------------------------------------
4 | 2 | 2016-09-12 18:05:29 |
--------------------------------------------
5 | 2 | 2016-09-12 18:03:00 |
--------------------------------------------
How can I get the last inserted record grouped by id_pers
.
The selection that I am making is:
select id, id_pers, max(created_at) as fecha_creacion
from observaciones group by id_pers
What it gives me back:
--------------------------------------------
id | id_pers | created_at |
--------------------------------------------
1 | 1 | 2016-09-12 17:03:45 |
--------------------------------------------
4 | 2 | 2016-09-12 18:05:29 |
--------------------------------------------
It returns a id=1
in the first record when it should be id=2
. However the id=4
gives it back to me well.
Columns are of type id => INT
, id_pers => INT
and created_at => TIMESTAMP
.
Thanks in advance.