Need SQL query to get latest chat message between me and each my contact when my contact list is displayed

58 Views Asked by At

I have the below tables in the database.

Users

  • id
  • name
  • email
  • created_at
  • updated_at

Contacts

  • id
  • user_id (foreign key to users table)
  • contact_id (foreign key to users table)
  • created_at
  • updated_at

Messages

  • id
  • sender_id (foreign key to users table)
  • receiver_id (foreign key to users table)
  • message
  • created_at
  • updated_at

All I want is to display my contact list along with latest chat message which happend between me and my each contact whether I am sender or receiver in that message.

Expecting below result

---------------------------------------------------------------------
| Contact Name | Latest Message |Message Time (messages.created_at)|
----------------------------------------------------------------
| John Doe        | Hello there      | 2023-03-09 03:17:55
| Martin          | Hi Martin        | 2023-03-08 12:20:10
0

There are 0 best solutions below