SamPaGa
SamPaGa

Reputation: 35

MySQL Query to Group Messages as Conversation

I need to show messages as conversation in my user's inbox. Grouped by sender and displaying the last message (either last message received from the sender or my latest reply to that sender).

So far my current MySQL query only shows all received messages without any grouping.

Here's my database structure:

+-----------------------------------------------------------------------------------+
|                                  users_messages                                   |
+-----------------------------------------------------------------------------------+
| message_ID | from_id | to_id | date | subject | body | unread | delete1 | delete2 |
+-----------------------------------------------------------------------------------+

+---------------------+
|        users        |
+---------------------+
| id | username | ... 
+----+----------+-----+

Here is my current query:

$result = $DB->query("SELECT p.*, p.sender as sender, m.*
FROM  " . DB_PREFIX . "messages p
LEFT JOIN " . DB_PREFIX . "members m ON p.sender=m.member_id
WHERE p.receiver='" . $SESSION->conf['member_id'] . "' AND delete2=0
ORDER BY p.senddate DESC
LIMIT " . (($page - 1) * $PREFS->conf['per_page']) . ", " . $PREFS->conf['per_page']);

Upvotes: 1

Views: 1557

Answers (1)

Mr Zorn
Mr Zorn

Reputation: 1913

Kind of messy - but should work for you:

SELECT 
    * 
FROM 
    user_messages 
WHERE 
    message_ID IN ( 
    SELECT 
        MAX(message_ID) 
    FROM 
        (SELECT 
            IF(m.from_id = <THE USER ID>, m.to_id, m.from_id) as other_user_id, 
            m.message_id 
        FROM 
            users_messages m 
        WHERE 
            m.from_id = <THE USER ID> OR m.to_id = <THE USER ID>) me 
    GROUP BY 
        other_user_id 
    ) 
ORDER BY 
    message_id DESC

Upvotes: 3

Related Questions