1

I need to get last conversation records by to_user in Descending order. I have table called messages. Please have a look on the following screen shot: enter image description here

I want the output in the following manner:

 from_user| to_user | message         | 
  241     |  226    |   How are you?  |
  241     |  256    | Hi test message |

I have tried this query:

SELECT * FROM `messages` where from_user=241 group by to_user order by created DESC

I am getting the following output which is wrong:

enter image description here

Thanks in advance.

Amuk Saxena
  • 1,521
  • 4
  • 18
  • 44
  • Why are you grouping by to_user? You will have to aggregate the fields in your select if you do so. You could use group_concat() to concat the different messages sent. But when grouping, the order doesn't make a lot of sense, because the grouped entries have different dates, so you would have to specify if you want to group by the newest or oldest message of the different groups. – Philipp Jun 09 '16 at 07:45

4 Answers4

5

Try his:

SELECT t1.* 
FROM `messages` AS t1
JOIN (
   SELECT to_user, MAX(created) AS created
   FROM `messages` 
   WHERE from_user=241
   GROUP BY to_user
) AS t2 ON t1.to_user = t2.to_user AND t1.created = t2.created
WHERE from_user=241
ORDER BY t1.created DESC
Giorgos Betsos
  • 71,379
  • 9
  • 63
  • 98
2
SELECT *
FROM
  (SELECT *
   FROM `messages`
   WHERE from_user=241
   ORDER BY created DESC) as test
GROUP BY to_user
Sadikhasan
  • 18,365
  • 21
  • 80
  • 122
1

Try this

SELECT * FROM `messages` where from_user=241 group by to_user order by id , created DESC
Wasiq Muhammad
  • 3,080
  • 3
  • 16
  • 29
1

If you want all posts of the from_user in one field (misunderstood the question I think):

SELECT group_concat(messages.message) 
    FROM messages 
    WHERE from_user = 241 
    GROUP BY to_user 
    ORDER BY MAX(id) DESC

You have to say by which criteria you want it to be ordered though. You can have the starting of the conversation or last message of the conversation.

Philipp
  • 2,787
  • 2
  • 25
  • 27