我正在尝试创建类似于会话的MySQL表格的输出,如下所示:
Content From To Date
Lorem 36 3 10-10-2014
Ipsum 3 36 10-12-2014
Dolor 36 4 11-10-2014
我希望它像对话一样输出,因此只显示两个用户之间的最后一条消息(按日期排序)。所以ID为36的用户会看到上面的表格,如:
Content From To Date
Ipsum 3 36 10-12-2014
Dolor 36 4 11-10-2014
所以“Lorem”将不会显示,因为Ipsum是同一用户之间的较新消息。
编辑:
我现在使用此查询,但如果用户自己发送,则不会输出最新消息:
SELECT content, sent
FROM personal_messages pm
INNER JOIN (
SELECT MAX( id ) id, from_user, to_user
FROM personal_messages
WHERE from_user = 46 OR to_user = 46
GROUP BY to_user, from_user
) pm2 ON pm.id = pm2.id
INNER JOIN users u ON pm.from_user = u.id
ORDER BY pm.sent
我希望有人可以帮助我,提前谢谢!
答案 0 :(得分:0)
知道可能要迟到才能回答,但是如果这有助于某些事情 - 以下查询只会执行OP - 4选择和2个联接所要求的内容。
$sql="
SELECT T2.maxDate, T2.user2_id, T2.ava, T2.userName,chat.user_to,chat.user_from,chat.body,chat.viewed FROM
(SELECT T1.user2_id, users.userName, users.ava, max(cdate) maxDate FROM
(SELECT chat.user_to user2_id, max(msg_time) cdate
FROM chat WHERE chat.user_from=18
GROUP BY chat.user_to
union distinct
(SELECT chat.user_from user2_id, max(msg_time) cdate
FROM chat WHERE chat.user_to=18
GROUP BY chat.user_from)) T1
inner join users on (users.userID = T1.user2_id)
group by T1.user2_id
order by maxDate desc) T2
join chat on (T2.maxDate = chat.msg_time) ORDER BY T2.maxDate DESC";