Finding rows with latest date by id mysql

I have these 2 tables I am trying to write a query that will help me select all rows that gives this result

users

idname
1test
2test2

logs

iduserIdmessagedate
11this is a test2020-10-07 12:57:14
21another reason2020-10-07 13:57:14
31another reason 22020-10-07 14:57:14
42another reason 32020-10-04 12:57:14
52another reason 42020-10-05 12:57:14
62another reason 42020-10-06 12:57:14

Output Table
I need to pass many user Ids like in this case (1,2) and get below table only return MAX (date) per row per userId

iduserIdmessagedate
31another reason 22020-10-07 14:57:14
62another reason 42020-10-06 12:57:14

Is this possible with one Query? This what I have but not working

SELECT 
id ,
userId ,
message,
date
FROM logs
WHERE userId IN (1,2)
ORDER BY date DESC;

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You may use the results of a window function ROW_NUMBER to retrieve these results.

SELECT
    id,userId,message,date
FROM (
    SELECT 
        *,
        ROW_NUMBER() OVER (
            PARTITION BY userId
            ORDER BY date DESC
        ) as rn
    FROM 
        logs
) t
WHERE rn=1 AND
      userId IN (1,2)
ORDER BY date DESC

and for older mysql versions

SELECT
    id,userId,message,date
FROM (
    SELECT 
        l.*,
        @row_num:=IF([email protected]_user_id,@row_num+1,1) as rn,
        @prev_user_id:=userId
    FROM 
        logs l
    CROSS JOIN (
        SELECT @row_num:=0, @prev_user_id:=NULL
    ) as vars
    ORDER BY userId, date DESC
    
) t
WHERE rn=1 AND
      userId IN (1,2)
ORDER BY date DESC


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x