Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select most recent record based on two conditions

Tags:

sql

mysql

I have user1 who exchanged messages with user2 and user4 (these parameters are known). I now want to select the latest sent or received message for each conversation (i.e. LIMIT 1 for each conversation).

SQLFiddle

Currently my query returns all messages for all conversations:

SELECT * 
FROM message 
WHERE (toUserID IN (2,4) AND userID = 1)
OR    (userID IN (2,4) AND toUserID = 1)
ORDER BY message.time DESC

The returned rows should be messageID 3 and 6.

like image 641
Chris Avatar asked Jan 18 '26 05:01

Chris


1 Answers

Assuming that higher id values indicate more recent messages, you can do this:

  • Find all messages that involve user 1
  • Group the results by the other user id
  • Get the maximum message id per group
SELECT *
FROM message
WHERE messageID IN (
    SELECT MAX(messageID)
    FROM message
    WHERE userID = 1 -- optionally filter by the other user
    OR toUserID = 1 -- optionally filter by the other user
    GROUP BY CASE WHEN userID = 1 THEN toUserID ELSE userID END
)
ORDER BY messageID DESC

Updated SQLFiddle

like image 92
Salman A Avatar answered Jan 20 '26 20:01

Salman A



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!