How can I get the last message from each conversation in mySQL? -


what looking for:
looking select query allows me select last message each conversation. conversation composed of rows have same users id, both side. example: 4-2 & 2-4.

message table:
id-----sender_id-----receiver_id-----body-----timestamp
1-------------------4---------------------2----------...-----------------...
2-------------------2---------------------4----------...-----------------...
3-------------------4---------------------2----------...-----------------...
4-------------------4---------------------2----------...-----------------...
5-------------------4---------------------3----------...-----------------...
6-------------------3---------------------4----------...-----------------...

result:
id-----sender_id-----receiver_id-----body-----timestamp
4-------------------4---------------------2----------...-----------------...
6-------------------3---------------------4----------...-----------------...

to last message conversation use group query last id (if it's incrementing) or last timestamp. user_1 user lower id, , user_2 user higher id of conversation:

select   least(sender_id, receiver_id) user_1,   greatest(sender_id, receiver_id) user_2,   max(id) last_id,   max(timestamp) last_timestamp   messages group   least(sender_id, receiver_id),   greatest(sender_id, receiver_id) 

you can actual message query this:

select m.*   messages m inner join (     select       least(sender_id, receiver_id) user_1,       greatest(sender_id, receiver_id) user_2,       max(id) last_id,       max(timestamp) last_timestamp           messages     group       least(sender_id, receiver_id),       greatest(sender_id, receiver_id)   ) s on least(sender_id, receiver_id)=user_1          , greatest(sender_id, receiver_id)=user_2          , m.id = s.last_id -- or last timestamp 

Comments

Popular posts from this blog

c# - Update a combobox from a presenter (MVP) -

How to understand 2 main() functions after using uftrace to profile the C++ program? -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -