SQL Limit results per column value [duplicate]

2019-08-07 09:37发布

问题:

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
)

回答1:

Perhaps this is what you're looking for:

SELECT userId, messageId FROM (
    SELECT userId, messageId,
        if(@uid = userId, @cnt := @cnt + 1, (@cnt := 0 || @uid := userId)) cnt
    FROM Messages
    ORDER BY userId, messageId DESC
) msg_list
WHERE cnt <= 5;


标签: mysql sql limit