获取pm消息的MAX结果

时间:2014-09-04 13:41:16

标签: php max

我试图获得两个用户之间每次对话的最后结果而没有优先权。我已经在线查看了一些例子,例如

[php Mysql Grouping and Ordering user messages together

和更高级的查询

[GROUP BY messages MySQL

我的数据库结构如下。 我的对话依赖于获取message_creatormessage_target的ID,以将其链接到一个聊天中。

message_id,
message_content,
message_target,
message_creator,
message_status, 
message_time

我需要message_status在查询中同时选择1 AND 2,这样如果用户已阅读最后一条消息,它仍会显示为对话中的最后一条消息。

这是我目前的查询。

$callmessage=" SELECT message_id,MAX(message_content) AS message_content ,message_target,message_status,message_creator,message_throughurl,MAX(message_time) AS message_time FROM messages WHERE message_target='$user1_id' OR message_creator='$user1_id' AND message_status=1 OR message_status=2 
    Group By 
    (if(message_creator > message_target,  message_creator,message_target))
     ,(if(message_creator > message_target,  message_target,message_creator)) 
    ORDER BY message_id DESC";

2 个答案:

答案 0 :(得分:0)

如果您想获取两个用户之间的最后一条消息,那么这应该有效:

SELECT * 
FROM messages 
WHERE ( 
    (message_creator='$user1_id' AND message_target='$user2_id')
    OR 
    (message_creator='$user2_id' AND message_target='$user1_id')
)
AND message_status IN (1,2)
ORDER BY message_id DESC
LIMIT 1

答案 1 :(得分:0)

确定。我已经解决了它的工作。这就是我对我的查询所做的,只需添加一些内容。

$user1_id= mysqli_real_escape_string($mysqli,$_SESSION['id']);
$callmessage="  SELECT * FROM messages WHERE message_id IN
    (SELECT MAX(message_id) AS message_id FROM
    (SELECT message_id, message_creator AS id_with
    FROM messages
    WHERE message_target = '$user1_id'
    UNION ALL
    SELECT message_id, message_target AS id_with
    FROM messages
    WHERE message_creator= '$user1_id') t
    GROUP BY id_with)";