好的,所以我一直试图找出我的用户收件箱的解决方案。
基本上,当用户查看其收件箱时,我希望它显示来自已发送消息的每个用户的最后一条消息。因此,例如,如果John消息Jane“消息1”,“消息2”,“消息3”。 Jane将在她的收件箱中看到最后一条消息“消息3”。我的意图是当她点击该消息时,她将看到整个帖子(我已经平方离开)。我实际上部分有这个工作,但是有一个问题。如果John然后消息Sarah“消息1”,“消息2”,“消息3”该查询将适用于Sarah,但将不再适用于Jane。
我似乎无法弄明白。这是我到目前为止所拥有的。任何建议都将不胜感激。
SELECT t1.*, u.username as from_username, u.user_type as from_usertype,
p.profile_picture
FROM messages t1
JOIN (
SELECT from_id, MAX(date) date
FROM messages
GROUP BY from_id
) t2 ON t1.from_id = t2.from_id AND t1.date = t2.date
LEFT JOIN users u ON u.id = t1.from_id
LEFT JOIN profiles p ON p.user_id = t1.from_id
WHERE t1.to_id = '{$loggeduser}'
AND t1.deleted = '0'
LIMIT {$pagination->items_per_page}
OFFSET {$pagination->offset}
答案 0 :(得分:0)
SELECT m.*,
u.username as from_username, u.user_type as from_usertype,
p.profile_picture
FROM (
SELECT DISTINCT
from_id
FROM messages
WHERE to_id = $loggeduser
AND deleted = 0
) md
JOIN messages m
ON m.id =
(
SELECT id
FROM messages mi
WHERE mi.to_id = $loggeduser
AND mi.from_id = md.from_id
AND mi.deleted = 0
ORDER BY
mi.to_id DESC, mi.from_id DESC, mi.date DESC, mi.id DESC
LIMIT 1
)
JOIN users u
ON u.id = md.from_id
JOIN profiles p
ON p.user_id = md.from_id