2

Hi I'm trying to make a messaging system with php and mysql.

The mysql table is simple: id sender receiver text timestamp

I'm trying to make the messaging somewhat like Facebook/Twitter so the list is in 'conversations' and the last message in the conversation is viewed.

This is what I have atm:

(SELECT * FROM messages WHERE receiver = 13 OR sender = 13 GROUP BY receiver,sender ORDER BY id ASC) ORDER BY id ASC
1
  • You can try by desc after group by keyword. Commented Feb 6, 2014 at 6:50

3 Answers 3

2
SELECT messages.* FROM messages, (SELECT MAX(id) as lastid FROM messages 
WHERE receiver = 13 OR sender = 13 
GROUP BY CONCAT(LEAST(receiver,sender),'.',GREATEST(receiver,sender))) as conversations
WHERE id = conversations.lastid
ORDER BY timestamp DESC

what you need is a unique conversation id between the chat-partners. i've simulated this with the subquery, hope this helps

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! This isn't my question, but I was looking for the same thing and this worked perfectly!
1

Use DESC for fetch new rows, default is ASC

   (SELECT * FROM messages WHERE receiver = 13 OR sender = 13 GROUP BY receiver,sender ORDER BY id DESC)

AND SET LIMIT 1 ,1 AFTER ORDER BY

I think you need to

(receiver = '{receiver id}' AND sender = '{sender id}' ) OR (receiver ='{sender id}' AND sender = '{receiver id}' )

7 Comments

This works but I can see a message I sent to someone else and the message they replied. I'm trying to make it one conversation with the last message sent between the 2 people displayed.
Put LIMIT 1,1 AFTER ORDER BY
Conversations I'm having with other people aren't displayed
Create Unique Session For Any chat And set for it receiver And sender.But my answer is ok!
change receiver = 13 OR sender = 13 to receiver = 13
|
0

UPDAte: I'm not sure if it works perfect:

SELECT * FROM messages 
WHERE receiver = 13
GROUP BY receiver,sender 
ORDER BY timestamp DESC
LIMIT 1

UNION ALL
SELECT * FROM messages 
WHERE sender = 13
GROUP BY receiver,sender 
ORDER BY timestamp DESC
LIMIT 1

to reverse the order:

ORDER BY timestamp DESC

4 Comments

The problem is I'm viewing multiple conversations. I need to just to view 1 per person and view the last message sent in the conversation.
you can use LIMIT 1 after ORDER
True but then I won't see conversations with other people.
can you explain more? because I dont get what you mean

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.