Possible Duplicate:
mysql: Using LIMIT within GROUP BY to get N results per group?
I'm trying to write a query that will function like a LIMIT
statement, but it will limit the results returned per distinct column value instead of the entire result set. I don't know the terminology to explain what I want precisely, so I'll use an example.
In this example (which is a much simplified version of what I'm actually trying to do) I'm trying to SELECT
the 5 most recent messages for each user in the system. The below table maps userIDs to messageIDs. Message IDs are assigned chronologically so a more recent message will have a higher ID value.
TABLE Messages (
userId int,
messageId int
)