我有一个消息表,其中包含字段id,时间,isread,消息,messagestatus,接收者和用户。我想检索发送或接收给其他任何用户的ID为1的用户的最新消息(基于时间)。
例如,如果ID为1(发送者)的用户向ID为2(接收者)的用户发送消息,而ID为2的用户向ID为1的用户发送消息。只能选择它们之间发送的最新消息
我已经存在的表如下:
我尝试了SELECT * from (SELECT MAX(time) as time ,sender,receiver from message group by sender,receiver) as f
where receiver=1 or sender=1 limit 20
,但是它仅显示发送者,接收者和时间,而其他列(如message,id,messagestatus和read)则被省略,而且它找不到两个用户之间发送的一般最新消息,而是找到之间发送的最新消息。当user1是发送方,另一个用户是接收方时,user1和另一个用户;当user1是接收方,另一个用户是发送方时,还会找到最后一条消息。
答案 0 :(得分:1)
如果您希望用户“ 1”发送或接收最新消息,请使用过滤功能,而不要使用select m.*
from messages m
where 1 in (m.sender, m.receiver) and
m.time = (select max(m2.time)
from messages m2
where (m2.sender = m.sender and m2.receiver = m.receiver) or
(m2.receiver = m.sender and m2.sender = m.receiver)
);
:
select m.*
from messages m
where 1 in (m.sender, m.receiver) and
m.id = (select id
from messages m2
where (m2.sender = m.sender and m2.receiver = m.receiver) or
(m2.receiver = m.sender and m2.sender = m.receiver)
order by m2.time desc, m2.id desc
limit 1
);
如果两条消息可能具有完全相同的时间戳,则:
<a href="#" class="button expanded vote" style="background: rgb(51, 204, 102) none repeat scroll 0% 0%; border-radius: 5px;" onclick="Poll.sendAnswer("Programn2015","Answer1","Answer2")">Vote</a>