Let's say I have a table called messages
with the columns:
id | from_id | to_id | subject | message | timestamp
I want to get the latest message from each user only, like you would see in your FaceBook inbox before you drill down into the actual thread.
This query seems to get me close to the result I need:
SELECT * FROM messages GROUP BY from_id
However the query is giving me the oldest message from each user and not the newest.
I can't figure this one out.
This is a standard problem.
Note that MySQL allows you to omit columns from the GROUP BY clause, which Standard SQL does not, but you do not get deterministic results in general when you use the MySQL facility.
I've added a filter on the
To_ID
to match what you're likely to have. The query will work without it, but will return a lot more data in general. The condition should not need to be stated in both the nested query and the outer query (the optimizer should push the condition down automatically), but it can do no harm to repeat the condition as shown.You should find out last
timestamp
values in each group (subquery), and then join this subquery to the table -Try this
this query return last record for every Form_id:
Just complementing what Devart said, the below code is not ordering according to the question:
The "GROUP BY" clause must be in the main query since that we need first reorder the "SOURCE" to get the needed "grouping" so:
Regards,
You need to order them.
SELECT * FROM messages GROUP BY from_id ORDER BY timestamp DESC LIMIT 1