skip to Main Content

I have two tables, tbl_msg and tbl_details.(Like the photo below)
I want to select the last message of each chat, like the image embedded with SQL, such as WhatsApp and Telegram chat lists.(sql code).
please help me. thank’s

table's

3

Answers


  1. This might be one option:

    select *
    from tbl_msg a join tbl_msg_details b on b.msg_id = a.msg_id
    where b.details_id = (select max(c.details_id)
                          from tbl_msg_details c
                          where c.msg_id = b.msg_id  
                         )
    
    Login or Signup to reply.
  2. One method is window functions:

    select md.*
    from (select md.*,
                 row_number() over (partition by msg_id order by time_st desc) as seqnum
          from tbl_msg_details md
         ) md
    where seqnum = 1;
    

    Note: You do not need tbl_msg unless there are columns from the table you want in the result set.

    Also, it is unclear if the "last message" is based on the time column or the id column. This uses the time column, but you can — of course — use the id if that is your definition of "last".

    Login or Signup to reply.
  3. Maybe with a "group by" and an "HAVING c.details_id = MAX(c.details_id)" it’s better no ?

    Like that :

    select *
    from tbl_msg a join tbl_msg_details b on b.msg_id = a.msg_id
    group by c.details_id
    HAVING c.details_id = MAX(c.details_id)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search