我的数据库中有一个表用于保存用户之间的消息。
表"dt_inbox"具有以下结构:
-messageid(PK)
-fromid=>由userid=A发起的消息
-toid=>发送给userid=B的消息
-conversationid=>会话id
-datesend=>发送消息的日期
-inbox_view=>标记0或1以了解消息是否已被读取
-inboxdelete=>标记0或1以了解消息是否已被删除
我正在尝试创建一个查询,以便获得用户ID a的所有消息列表:-由用户A发送给用户B(C、D、E…),或由用户B发送给用户A=>从id A->toid B或从id B->toid A发送的消息应显示在一行中
-id/toid中的每对用户都应该出现在一行中
-显示用户A和B之间最后一条消息的datemax(datesend)
-按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,我只想在这个用户和所有其他用户之间有最后一条消息,如果消息来自id或toid 12,则不做任何区别
我希望我的结果为:
messageid conversationid user1 user2 direction datemax messagesnr unreadsrn
1239 2139 12 159 from date 1 0
1238 2138 12 22 to date 1 1
新列"direction"将是一个标志,显示最后一条消息是否来自或到userid=12。
提前感谢您的帮助,我真的被阻止了:(
没有尝试过;-)但也许这是正确的做法。
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