问题
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 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:
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