我正在开发一个mysql / php私人消息系统,我遇到了使用MYSQL代码的问题。我想要在用户之间的对话中发送/接收最后一条消息。喜欢这个facebook https://www.facebook.com/messages/页面。 (用文字解释这一点并不容易。)
我的消息mysql表是这样的:
`id` -> unique ID, autoincremented
`message_from` -> sender user ID
`message_to` -> receiver user ID
`message` -> message
`date_created`
`ip`
`status` -> read or not read
在我脑海中不清楚如何做到这一点,所以我没有要显示的初始脚本。
答案 0 :(得分:2)
这将为您提供每个聊天的最新消息。每个聊天都由message_from和message_to ID标识。
SELECT
*
FROM messages m1
WHERE date_created = (SELECT MAX(m2.date_created) FROM messages m2 WHERE m1.message_from = m2.message_from AND m1.message_to = m2.message_to)
如果您想进行特定聊天,只需添加
即可AND message_from = $yourUserId
AND message_to = $yourOtherUserId
很抱歉,如果这不是您要找的,我不会点击Facebook链接。
答案 1 :(得分:1)
首先构建查询以获取所有会话和最后一条消息的发送日期;对话被定义为发送者和接收者的唯一组合。
SELECT message_from, message_to, MAX(date_created) AS max_date
FROM messages
WHERE message_from = :user OR message_to = :user
GROUP BY message_from, message_to
:user
只是当前登录用户的占位符。
要从对话中的最后一条消息中获取实际数据,您必须将结果与原始表一起加入:
SELECT message, date_created, status
FROM messages
JOIN (
SELECT message_from, message_to, MAX(date_created) AS max_date
FROM messages m
WHERE message_from = :user OR message_to = :user
GROUP BY message_from, message_to
) AS lm ON m.date_created=lm.max_date AND m.message_from=lm.message_from AND m.message_to=lm.message_to
答案 2 :(得分:1)
SELECT f . * FROM ( SELECT * FROM message a WHERE ( LEAST( a.message_from, a.message_to ) , GREATEST( a.message_from, a.message_to ) , a.sent) IN (SELECT LEAST( b.message_from, b.message_to ) AS x, GREATEST( b.message_from, b.message_to ) AS y, MAX( b.date_created ) AS msg_time FROM message b GROUP BY x, y))f WHERE ".$mainUser." IN (f.message_from, f.message_to )ORDER BY f.date_created DESC limit $pageLimit,".$per_page
只需复制此查询并在phpmyadmin中查看
答案 3 :(得分:0)
也许是这样的:
SELECT
*
FROM
tblMessage
JOIN(
SELECT
MAX(date_created) AS maxCreated,
message_from
FROM
tblMessage
GROUP BY
message_from
) AS Latest
ON tblMessage.date_created=Latest.maxCreated
AND tblMessage.message_from=Latest.message_from
答案 4 :(得分:0)
您可以使用此
$recup_messages = mysqli_query($connection, SELECT * FROM messages WHERE
(message_from = $yourUserId AND message_to = $yourOtherUserId) OR (message_from = $yourUserId AND message_to = $yourOtherUserId ) ") or die(mysqli_error($connection));
while($affichage = mysqli_fetch_assoc($recup_messages))
{
$message_from = $affichage['message_from'];
$message = $affichage['message'];
echo "From : $message_from <br> $message <br><br>";
}
这将像facebook一样接着显示你的消息。现在你必须按照你想要的方式设置它并添加有关日期和其他东西的信息
答案 5 :(得分:0)
这对我有用
SELECT t1.*
FROM messages AS t1
INNER JOIN
(
SELECT
LEAST(sender_id, receiver_id) AS sender_id,
GREATEST(sender_id, receiver_id) AS receiver_id,
MAX(id) AS max_id
FROM messages
GROUP BY
LEAST(sender_id, receiver_id),
GREATEST(sender_id, receiver_id)
) AS t2
ON LEAST(t1.sender_id, t1.receiver_id) = t2.sender_id AND
GREATEST(t1.sender_id, t1.receiver_id) = t2.receiver_id AND
t1.id = t2.max_id
WHERE t1.sender_id = :id OR t1.receiver_id = :id
绑定了:id的地方。