Skip to content

Instantly share code, notes, and snippets.

@hassanrazadev
Last active July 4, 2024 03:25
Show Gist options
  • Save hassanrazadev/dbc21e5b97643e211feba23f0b1afe5d to your computer and use it in GitHub Desktop.
Save hassanrazadev/dbc21e5b97643e211feba23f0b1afe5d to your computer and use it in GitHub Desktop.
Get latest conversation with last message per user. (MySQL query)
SELECT
*
FROM
messages,
(
SELECT
MAX(id) as lastid
FROM
messages
WHERE
(
messages.to_id = 1 -- ID to compare with (logged in users's ID)
OR messages.from_id = 1 -- ID to compare with (logged in users's ID)
)
GROUP BY
CONCAT(
LEAST(messages.to_id, messages.from_id),
'.',
GREATEST(messages.to_id, messages.from_id)
)
) as conversations
WHERE
id = conversations.lastid
ORDER BY
messages.created_at DESC
/* Another way using join */
SELECT
*
FROM messages m
INNER JOIN
(
SELECT MAX(id) as lastid
FROM messages
WHERE
(
messages.to = 1 -- ID to compare with (logged in users's ID)
OR
messages.from_id = 1 -- ID to compare with (logged in users's ID)
)
GROUP BY
CONCAT(
LEAST(messages.to_id, messages.from_id),
'.',
GREATEST(messages.to_id, messages.from_id)
)
) conversations
ON conversations.lastid = m.id
ORDER BY
m.created_at DESC
@JoanUniverse
Copy link

Nice

@hsemix
Copy link

hsemix commented Sep 11, 2022

Great

@NavinduK
Copy link

U saved me ❤️

@hassanrazadev
Copy link
Author

hassanrazadev commented Jan 30, 2023

Here is how you can achieve this within Laravel.
https://gist.github.com/hassanrazadev/767046c36aba528918c63bdb8f47ab25

@MohammedElattar
Copy link

How can i get the number of unread messages that from that user and the receiver is the current loggedUser

@AlekseyVerba
Copy link

thank you a lot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment