mysql: Get last conversation records by user [duplicate]

二次信任 提交于 2021-02-08 09:49:18

问题


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:

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:

Thanks in advance.


回答1:


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



回答2:


SELECT *
FROM
  (SELECT *
   FROM `messages`
   WHERE from_user=241
   ORDER BY created DESC) as test
GROUP BY to_user



回答3:


Try this

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



回答4:


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.



来源:https://stackoverflow.com/questions/37719720/mysql-get-last-conversation-records-by-user

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!