我有两个表,conversation_tbl和conversation_reply_tbl
conversation_reply_tbl
-------------------------
| conversation_reply_id| //auto increment id
| reply_message | //message text
| user_id | //the user who sent the message
| datetime_sent | //date and time of message sent
| status | //values '0' or '1' (read or not)
| conversation_id | //relation to the conversation
-------------------------
conversation_tbl
-------------------------
| conversation_id | //auto increment id
| from_user | //the user who sent the message
| to_user | //the recipient
| datetime_created | //date of the message created
| gallery_id |//the gallery where the message started from
-------------------------
现在,我使用conversation_reply_tbl
存储会话中发生的所有消息,并使用conversation_tbl
存储会话主数据。
现在,我想选择用户参与的所有会话,但我想显示每个会话的最新消息,就像在着名网站和应用程序(例如'WhatsApp'或'Facebook')中所做的一样。
这可以在一个查询中完成,还是必须使用PHP函数?
答案 0 :(得分:1)
以下是使用一个查询获取该信息的方法:
select t.*,
last.*
from conversation_tbl t
inner join (select conversation_id, max(conversation_reply_id) conversation_reply_id
from conversation_reply_tbl
group by conversation_id) all_lasts
on all_lasts.conversation_id = t.conversation_id
inner join conversation_reply_tbl last
on last.conversation_reply_id = all_lasts.conversation_reply_id
left join (select conversation_id
from conversation_reply_tbl
where user_id = :the_user_id
group by conversation_id) user_conv
on user_conv.conversation_id = t.conversation_id
where ( user_conv.conversation_id is not null
or t.to_user = :the_user_id )
请注意left join
,因为目标用户可能尚未回复消息,而是启动消息的 to_user 。 where
子句使两种情况都成为or
:如果消息线程有用户的消息,或者用户是发起消息的目标,则查询应返回该对话。
答案 1 :(得分:0)
如果我理解您正在尝试正确执行的操作,那么这样的内容会在提供适当的conversation_id时为您提供记录。
获取用户所属的对话
SELECT conversation_id FROM conversation_tbl WHERE from_user = ?
使用该ID,获取最后发送的消息。
SELECT datetime_sent, reply_message FROM conversation_reply_tbl
WHERE datetime_sent IN (SELECT MAX(datetime_sent)
FROM conversation_reply_tbl WHERE conversation_id = ? )
答案 2 :(得分:0)
我假设您将所有会话消息保存在conversation_reply_tbl表的reply_message列下。
在这种情况下,你可以尝试这个
SELECT T2.conversation_id, T2.reply_message
FROM conversation_tbl T1 INNER JOIN conversation_reply_tbl T2 ON
T1.conversation_id = T2.conversation_id
WHERE (T1.from_user = $userID OR T1.to_user = $userID)
GROUP BY T1.conversation_id
ORDER BY T2.datime_sent DESC;