MySQL获取最新的会话消息

时间:2016-12-12 06:46:50

标签: mysql sql database chat

我正在创建一个应用,用户可以与其他用户聊天(1对1,而不是群聊)。我有一个MySQL表,存储来自每个用户的所有消息,如:

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`

如何从最新到最旧的abc123获取AND的最新消息,例如:

from_id to_id message time

abc123 p0tat0 I missed the bus 3456

def456 abc123 How was last night? 2345

如果重要的话,

time将始终按消息表中的升序排列。

非常感谢任何帮助。谢谢^。^

SELECT *, 'from' as direction FROM 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 direction FROM messages WHERE to_username='admin' AND 'time' = ( SELECT MAX('time') FROM messages WHERE to_username='admin' OR to_username='admin' )

1 个答案:

答案 0 :(得分:1)

试试这个

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' )