MySQL get latest conversation messages

久未见 提交于 2019-11-28 13:57:19

问题


I'm making an app where users can chat to other users (1 on 1, NOT a group chat). I have a MySQL table that stores all the messages from every user, like:

from_id   to_id          message             time
abc123    def456         Hello               789
def456    abc123         What's up?          1234`
def456    abc123         How was last night? 2345
abc123    p0tat0         I missed the bus    3456
def456    p0tat0         I hate you :(       4567`
def456    another_user   I hate Potato!      5678`

How can I get the latest message from AND to abc123 sorted from newest to oldest, like:

from_id to_id message time

abc123 p0tat0 I missed the bus 3456

def456 abc123 How was last night? 2345

time will always be in an ascending order in the messages table if that matters.

Any help would be very much appreciated. Thank you ^.^

SELECT *,'from' as directionFROM messages WHERE from_username='admin' AND 'time' = ( SELECT MAX('time') FROM messages WHERE from_username='admin'OR to_username='admin')

UNION ALL

SELECT *,'to' as directionFROM messages WHERE to_username='admin' AND 'time' = ( SELECT MAX('time') FROM messages WHEREto_username='admin' ORto_username='admin' )


回答1:


Try this

SELECT * FROM
messageTable
WHERE from_id='abc123'
AND `time` = ( SELECT MAX(`time`) FROM messageTable WHERE from_id='abc123' )

UNION ALL

SELECT * FROM
messageTable
WHERE to_id='abc123'
AND `time` = ( SELECT MAX(`time`) FROM messageTable WHERE to_id='abc123' )


来源:https://stackoverflow.com/questions/41095463/mysql-get-latest-conversation-messages

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