I have the following table sir_ter_conversa
which is a history of conversations.
id|idterreno|idincorporadora|idusuario|msg|data
1 | 1 | 771 | 771 | a |2018-05-27 10:20:00
2 | 1 | 771 | 773 | b |2018-05-27 10:30:00
3 | 1 | 771 | 771 | c |2018-05-27 11:20:00
4 | 1 | 771 | 773 | d |2018-05-27 11:35:00
5 | 2 | 772 | 775 | e |2018-05-27 13:25:00
idterreno is what groups the conversations, incorporating id is the client, user id is who wrote the message that can be the user or the admin (id 773).
I need to make a query that brings the grouped conversations together and who made the last interaction based on the last id or date. In that case it would bring:
id|idterreno|idincorporadora|idusuario|msg|data
4 | 1 | 771 | 773 | d |2018-05-27 10:20:00
5 | 2 | 772 | 775 | e |2018-05-27 10:30:00
I tried the option below, but the problem is that it did not bring the last id that you entered, brought the first id.
SELECT idterreno, idusuario, max(data)
FROM sir_ter_conversa
GROUP BY idterreno
In this query it brings idusuario 771 and not 773:
idterreno|idusuario|max(data)
1 | 771 |2018-05-27 10:20:00
2 | 775 |2018-05-27 10:30:00