简体   繁体   English

MySQL:在INBOX中每位用户显示最后一条消息

[英]MySQL: Show last messages in INBOX one per User

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. 我需要像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. 我尝试了GROUP BY,但结果不准确。 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']);
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. 我尚未测试过,因此可能有所疏忽,但一个选择是,您可以对发件人和收件人和t1.message_ID <t3.message_ID进行user_messages自联接。 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. 因为来自t1的一对消息之间的最新消息在t3中没有联接候选者,并且它是左联接,所以t3列将为空,您可以在where子句中选择该消息以获取最新消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM