我的数据库中有一个表,可以在用户之间保存消息。
表" dt_inbox"具有以下结构:
- messageid(PK)
- fromid => userid = A发起的消息
- toid =>消息发送到userid = B
- conversationid =>对话的身份
- datesent =>发送消息的日期
- inbox_view =>标志0或1以知道是否已读取消息
- inboxdelete =>标志0或1以了解消息是否已被删除
我尝试创建一个查询,以获得用户ID A的所有消息的列表: - 由用户A发送给用户B(C,D,E ......),或者由用户B(C,D,E ...)发送给用户A =>发送消息的消息A - > toid B或fromid B - > toid A应出现在一行中 - 来自/ toid的每一对用户应该出现在一行中 - 显示用户A和B之间的最后一条消息的datemax(datesent) - 按datemax订购 - inboxdeleted = 0和inbox_view = 0。
这是我的查询,但结果与预期不符,对于userid = 12:
SELECT messageid, conversationid, fromid, toid,
(SELECT MAX(datesent) FROM dt_inbox dd WHERE dd.conversationid = d.conversationid) as datemax,
(SELECT count(*) FROM dt_inbox dd WHERE dd.conversationid=d.conversationid) as messagesnr,
(SELECT count(*) FROM dt_inbox dd WHERE dd.conversationid=d.conversationid AND dd.inboxview=0 AND toid=12) as unreadsrn
FROM dt_inbox d
WHERE (toid = 12 AND inboxdelete=0
OR fromid = 12 AND inboxdelete=0)
GROUP BY conversationid
ORDER BY datemax DESC
这给出了以下结果:
messageid conversationid fromid toid datemax messagesnr unreadsrn
1239 2139 12 159 date 1 0
1238 2138 12 22 date 1 1
1237 2137 12 159 date 1 0
1236 2136 12 22 date 1 0
1235 2135 159 12 date 1 1
1234 2134 159 12 date 1 1
在此示例中,对于userid = 12,我希望此用户与所有其他用户之间只有最后消息,如果消息来自fromid或toid 12 < / p>
我希望我的结果为:
messageid conversationid user1 user2 direction datemax messagesnr unreadsrn
1239 2139 12 159 from date 1 0
1238 2138 12 22 to date 1 1
新专栏#34;方向&#34;将是一个标志,显示最后一条消息是否来自或来自userid = 12.
在此先感谢您的帮助,我真的被阻止了:(
答案 0 :(得分:0)
没试过;-) 但也许是正确的方法。
SELECT max(messageid) as messageid, conversationid, fromid, toid,
datemax, messagesnr, unreadsrn, toid as tmp_toid
FROM dt_inbox
WHERE fromid=12
GROUP BY toid
JOIN
SELECT max(messageid) as messageid, conversationid, fromid, toid,
datemax, messagesnr, unreadsrn, fromid as tmp_fromid
FROM dt_inbox
WHERE toid=12
GROUP BY fromid
ON tmp_toid=tmp_fromid