gpt4 book ai didi

MySQL 在我的收件箱中每个用户只有一封邮件(最新的)

转载 作者:太空宇宙 更新时间:2023-11-03 12:33:49 26 4
gpt4 key购买 nike

请帮帮我,我只想在收件箱中为每个用户显示一条消息(最新消息)。因此,如果我正在与 user1user2user3 交换消息,而不是像这样在收件箱中显示他们的所有消息:

user2 - message 6
user3 - message 5
user2 - message 4
user1 - message 3
user1 - message 2
user1 - message 1

我只需要像这样在我的收件箱中显示来自他们每个人的最新消息。

user2 - message 6
user3 - message 5
user1 - message 3

这是我的表格。

+-----------------------------------------------------------------------------------+
| messages |
+-----------------------------------------------------------------------------------+
| message_ID | sender |receiver| date | subject | body | unread | delete1 | delete2 |
+-----------------------------------------------------------------------------------+

+---------------------+
| members |
+---------------------+
| id | username | ...
+----+----------+-----+

到目前为止这是我的查询。

SELECT p.*, p.sender as sender, m.*
FROM messages p
LEFT JOIN members m ON p.sender=m.member_id
WHERE p.receiver='<CURRENT_USER>' AND delete2=0
GROUP BY p.sender ORDER BY p.date DESC
LIMIT 5

最佳答案

    SELECT p.*, p.sender as sender, m.*
FROM `messages` p
INNER JOIN (SELECT sender,
MAX(message_ID) as last_message_id
FROM `messages`
WHERE receiver='<CURRENT_USER>' AND delete2=0
GROUP BY `sender`) t2 ON t2.sender = p.sender
AND t2.last_message_id = p.message_ID
LEFT JOIN members m ON p.sender = m.member_id
WHERE receiver='<CURRENT_USER>' AND delete2=0
ORDER BY p.date DESC
LIMIT 5

关于MySQL 在我的收件箱中每个用户只有一封邮件(最新的),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14176337/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com