I have two tables one is for users and other is for messages i want the latest messages of every user who sent the message to user 1 my code is below
SELECT u.profile_pic
, u.username
, u.firstname
, u.lastname
, m.message_from
, m.message_body
FROM user u
JOIN messages m
ON m.message_from = u.user_no
WHERE m.message_to = $userno
ORDER
BY m.sent_time DESC
Try adding the field of the ORDER BY clause into your selection:
SELECT u.profile_pic
, u.username
, u.firstname
, u.lastname
, m.message_from
, m.message_body
, m.sent_time
FROM user u
JOIN messages m
ON m.message_from = u.user_no
WHERE m.message_to = $userno
ORDER
BY m.sent_time DESC
Use LEFT JOIN
to message table on same user and newer sent_time. The latest of each user is the one that doesn't have such message:
SELECT profile_pic,username,firstname,lastname,messages.message_from,messages.message_body
FROM user
JOIN messages ON user.user_no = messages.message_from
LEFT JOIN messages AS newermessages ON user.user_no = newermessages.message_from AND messages.sent_time < newermessages.sent_time
WHERE messages.message_to = '$userno'
AND newermessages.id IS NULL
ORDER BY messages.sent_time DESC
The latest message from each user:
SELECT a.*
FROM messages a
JOIN
( SELECT message_from
, MAX(sent_time) max_sent_time
FROM messages
GROUP
BY message_from
) b
ON b.message_from = a.message_from
AND b.max_sent_time = a.sent_time;
The remainder of this problem has been left as an exercise for the reader.
It would be easier to give you an answer if you could include your table structures (is there a unique id on the messages
table?). But from the information in your question, this should work:
SELECT
u.profile_pic,
u.username,
u.firstname,
u.llastname,
m.message_from,
m2.message_body
FROM user u
JOIN (SELECT message_from,message_to,max(sent_time)
FROM messages
GROUP BY message_from,message_to) m
ON user.user_no = messages.message_from
AND messages.message_to = '$userno'
JOIN messages m2 ON m.message_from = m2.message_from
AND m.message_to = m2.message_to
AND m.sent_time = m2.sent_time
Basically, the subselect will pull out all of the latest messages from one user to another, which you then join against to filter out all the others.