如何在数据库查询中对所有对话(消息)进行分组

时间:2019-05-21 12:44:43

标签: php mysql sql

我有一个看起来像这样的数据库:

https://imgur.com/zUeW0Vc

我目前使用以下查询来获取特定登录用户(toid)的消息列表

SELECT 
photo,forename,surname,m.status,datetime,m.type,message,timestamp
FROM messages m 
LEFT JOIN users ON users.userID = m.fromid
WHERE toid = '$userID' ORDER BY datetime DESC 

然后我使用foreach($ messages as $ m)

然后回显一些向用户显示消息的代码。

当前与屏幕截图中一样,有来自相同fromid和toid的消息,并且当前同时打印这两个消息。

我想知道是否有一种方法可以将它们分组并仅将其显示为一条消息,但显示最近收到的消息吗?

我的php循环代码

 <?foreach ($messages as $m):?>


<li <?if ($m->status == "0"){?> class="unread" <?}?>>
<a href="dashboard-messages-conversation.html">
<div class="message-avatar"><img src="https://process.filestackapi.com/resize=width:960,height:960,fit:crop/<?echo $m->photo;?>" alt="" /></div>

<div class="message-by">
<div class="message-by-headline">
<h5><?echo $m->forename . " " . $m->surname;?> <?if ($m->status == "0"){?> <i>Unread</i><?}?></h5>
<span><? time_stamp($m->timestamp);?></span>
</div>
<p><?echo truncate($m->message, 100);?></p>
</div>
</a>
</li>



<?endforeach;?>

2 个答案:

答案 0 :(得分:0)

您可以使用相关子查询:

select m.*
from messages m
where m.timestamp = (select max(m2.timestamp)
                     from messages m2
                     where (m.toid, m.fromid) in ( (m2.toid, m2.fromid), (m2.fromid, m2.toid))
                    );

答案 1 :(得分:0)

如果您只想获取最新消息,因为您正在为单个用户选择消息,则需要将TOP子句添加到select语句中。

SELECT TOP 1
photo,forename,surname,m.status,datetime,m.type,message,timestamp
FROM messages m 
LEFT JOIN users ON users.userID = m.fromid
WHERE toid = '$userID' ORDER BY datetime DESC 

如果您想要多个用户的最新消息,则可能会对按fromid分组的消息进行自我联接,并获取fromid和max datetime来过滤消息。

SELECT 
photo,forename,surname,m.status,datetime,m.type,message,timestamp
FROM messages m 
inner join
(
    SELECT fromid, max(datetime) as lastmessage
    from messages
    group by fromid
) as filter ON m.fromid = filter.fromid
LEFT JOIN users ON users.userID = m.fromid
ORDER BY surname, forename