问题
Here's my problem, in my inbox it shows multiple messages that I received from one user only. I need to to display my inbox just like facebook. Showing only one message per one user. Much like a conversation view. Wherein, the last message between me and a user is showed in the inbox (either his last message, or my last reply to him).
I have tried GROUP BY, but the results are not accurate. Some recent messages are not displayed and it is not sorted by date of last conversation.
Here's my database structure:
+-----------------------------------------------------------------------------------+
| users_messages |
+-----------------------------------------------------------------------------------+
| message_ID | sender |receiver| date | subject | body | unread | delete1 | delete2 |
+-----------------------------------------------------------------------------------+
+---------------------+
| members |
+---------------------+
| 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
GROUP BY p.sender ORDER BY p.senddate DESC
LIMIT " . (($page - 1) * $PREFS->conf['per_page']) . ", " . $PREFS->conf['per_page']);
回答1:
SELECT t1.*, t2.*
FROM
users_messages AS t1
LEFT JOIN members AS t2
ON t1.sender = t2.id
LEFT JOIN users_messages AS t3
ON t1.sender = t3.sender AND t1.receiver = t3.receiver
AND t1.message_ID < t3.message_ID
WHERE (t1.sender = @userid OR t1.receiver = @userid) AND t3.message_ID IS NULL
I haven't tested so may have made an oversight but one option is you can do a user_messages self join on sender and reciver and t1.message_ID < t3.message_ID. Because the most recent message between a pair from t1 has no join candidates in t3 and it is a left join then the t3 columns will be null and you can select for this in the where clause to get the most recent.
来源:https://stackoverflow.com/questions/14152697/mysql-show-last-messages-in-inbox-one-per-user