Search code examples
mysqlgroupwise-maximum

MySQL grouping and getting newest rows


I would like to get newest row in column , But i need to get them just before grouping them each other. If i put Order by after group by, mysql ordering them which they before grouped.

What i tried to do, grouping messages for user's last messages each other ( like a facebook chat . )

If client had a 3 conversations , he/she need to see message list as last dialog :

( Suppose that , the mobile user nickname is Rob, and he is listing his message history... )

Rob -> Thomas ( Hello, I will be back asap. )

Dyne -> Rob (Where are you ?)

Rob -> Danilla (How re you ?)

SELECT 
    u.userNickName, 
    u.userFBID, 
    m.didRead, 
    max(m.messageID) messageID, 
    m.messageContent, 
    m.srcUserID, 
    m.destUserID, 
    m.messageSendDate
FROM 
users u, messages m
WHERE
(m.srcUserID='122' || m.destUserID ='122')
AND
u.userID =  m.destUserID
GROUP BY
u.userNickName

Solution

  • I solved my question with using subquery and group by with following SQL Statement :

    SELECT 
        u.userNickName,
        u.userFBID,
        m.didRead,
        m.messageID,
        m.messageContent,
        m.srcUserID,
        m.destUserID,
        m.messageSendDate 
    FROM 
        users u, 
        messages m 
    WHERE 
        (u.userID = m.srcUserID or u.userID = m.destUserID) 
    AND 
    CASE 
        WHEN m.srcUserID='122' THEN u.userID= m.destUserID
        WHEN m.destUserID ='122' THEN u.userID= m.srcUserID
        ELSE -1
    END 
    AND 
    m.messageID in (select max(m.messageID) from users u, messages m where (u.userID = m.srcUserID or u.userID = m.destUserID) group by u.userNickName);