I’m trying to group messages in conversations, so they can be read as a conversation.
This is what I have right now
Table messages
id | from | to | message | timestamp
1 | 1 | 2 | 'Hello' | 1351257766
2 | 1 | 3 | 'Hey!' | 1351257767
3 | 2 | 1 | 'Hay!' | 1351257768
Whereas the messages.from and messages.to fields correspond to a row in the users table.
What I want to do is: (not in the same query)
a. Get a list of the last messages of all the conversations from a user (so where either from or to is equal to a given user.id
b. Get all the messages that belong to a conversation.
SELECT
-- From-user:
users_from.id AS from_id,
users_from.username AS from_username,
users_from.nickname AS from_nickname,
users_from.username_safe AS from_username_safe,
users_from.password AS from_password,
users_from.email AS from_email,
users_from.rank AS from_rank,
users_from.email AS from_email,
users_from.ip AS from_ip,
users_from.last_online AS from_last_online,
users_from.register_stamp AS from_register_stamp,
users_from.state AS from_state,
users_from.icon AS from_icon,
-- To-user:
users_to.id AS to_id,
users_to.username AS to_username,
users_to.nickname AS to_nickname,
users_to.username_safe AS to_username_safe,
users_to.password AS to_password,
users_to.email AS to_email,
users_to.rank AS to_rank,
users_to.email AS to_email,
users_to.ip AS to_ip,
users_to.last_online AS to_last_online,
users_to.register_stamp AS to_register_stamp,
users_to.state AS to_state,
users_to.icon AS to_icon,
-- Messages:
messages.id,
messages.from,
messages.to,
messages.message,
messages.timestamp
FROM messages
-- Some joins to get the userdata
INNER JOIN users AS users_to
ON messages.to = users_to.id
INNER JOIN users AS users_from
ON messages.from = users_from.id
-- We only want the latest messages:
RIGHT JOIN (
SELECT
max(messages.id) AS maxid,
messages.from,
messages.to
FROM messages
WHERE messages.to = {userid} OR messages.from = {userid}
) limiter
ON messages.id = limiter.maxid
This is what I am using right now, but it isn’t working. It returns only one of the conversations.
I hope you guys can help me make this work!
UPDATE:
The answer that was given did not work. When user-1 sent a message to user-2, it worked. However when user-2 replied, it began a separate conversation (as a new row in the result).
Your query is close, but I think you need to group by the users as well. This is one approach
Your definition of conversation appears to be having the same two users. For this, use
in:By the way,
fromandtoare bad column names, becausefromis a reserved word.