Question

This is my mysql table structure:

msgid | senderid | sender | recipientid | recipient | title | message | date 

I'm looking to present in inbox for my private messaging system as Facebook have done. That is, each conversation is output ONE TIME from the table irrespective of whether it is incoming or outgoing. For example:

My username is 'admin'.

USER   |   MESSAGE       |   DATE   |  DIRECTION
Dan    | Hello           |  1/2/10  | Incoming
Bob    | How are you Bob?|  30/1/10 | Outgoing

The problem is not repeating the username because of differing directions. For example:

USER   |   MESSAGE       |   DATE   |  DIRECTION
Dan    | Hello           |  1/2/10  | Incoming
Bob    | How are you Bob?|  30/1/10 | Outgoing
Bob    | Hi admin        |  30/1/10 | Incoming

So I need to make sure that the only message that shows is the newest communication irrespective of the direction (i.e., the newest message with another user, irrespective of whether that user is the 'sender' or 'recipient').

I'm using PHP/MYSQL for this website. I've tried thousands of ways to do this but I just can't figure it out. It might be that my database is incorrectly structured. I will be online for a few hours (and will continually check after that) so feel free to ask any questions.

Was it helpful?

Solution 2

I have somewhat solved my own question with the following:

SELECT * FROM (
    SELECT * FROM (
         (SELECT id, reciever, recieverid, message, datetime FROM messages WHERE sender = '$user')
       UNION
          (SELECT id, sender, senderid, message, datetime FROM messages WHERE reciever = '$user')
          ) as t
       ORDER BY datetime DESC
    ) as t2
GROUP BY reciever ORDER BY datetime DESC

It seems to do the trick, although I don't know which messages are incoming or outgoing. I'll know if it works properly when I have a chance to invite some actual users.

OTHER TIPS

If I understand correctly this should do what you need:

SELECT
IF(senderid = :userId,recipient,sender) AS USER,
message,
date,
IF(senderid = :userId,'Outgoing','Incoming') AS DIRECTION
FROM message 
WHERE senderid = :userId OR recipientid = :userId 
ORDER BY date DESC

The USER and DIRECTION is determined based on whether this user is the sender or not.

If you are only interested in the latest message you can add a LIMIT to this query.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top