I build chat application with messages table.
I try to select 3 recent messages for each user that correspondent with specific user like that: user 17 has 3 users that correspondent with him, select last 3 messages for each user
17 22
22 17
22 17
19 17
17 19
19 17
21 17
17 21
17 21
I tried to write query, I got the good result for all users except one - the first or the last user that select for him more than 3 messages. the query:
    SELECT *, 
         DATE_FORMAT((FROM_UNIXTIME(m1.create_time)),'%k:%i, %d.%m.%Y') 
         as create_time_display
    FROM t_messages m1
    WHERE (m1.to =17 OR m1.from =17)  AND (
        SELECT COUNT(*) 
        FROM t_messages  m2
        WHERE m1.from = m2.from AND m2.id >= m1.id AND
        (m2.to = 17 OR m2.from = 17)
    ) <=3`
Any ideas how I can make it work well?
Thanks.
 
     
    