I have a table in my database saving messages between users.
The table "dt_inbox" has the following structure :
- messageid (PK)
- fromid => message initiated by userid=A
- toid => message sent to userid=B
- conversationid => id of the conversation
- datesent => date of message sent
- inbox_view => flag 0 or 1 to know if message has been read
- inboxdelete => flag 0 or 1 to know if message has been deleted
I'm trying to create a query in order to have a list of all messages for userid A: - sent by user A to user B(C,D,E...) , or sent by user B (C,D,E...) to user A => message sent fromid A -> toid B or fromid B -> toid A should appear in one line.
- each couple of users fromid/toid should appear in one line.
- showing datemax(datesent) of last message between user A and B
- ordered by datemax
- inboxdeleted = 0 and inbox_view=0.
Here is the query I have, but the result is not as expected, for 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
This give the following result :
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
In this example for userid=12, I want to have only the message between this user and all others, 一条消息, ,
I want my result as :
messageid conversationid user1 user2 direction datemax messagesnr unreadsrn
1239 2139 12 159 from date 1 0
1238 2138 12 22 to date 1 1
the new column "direction" will be a flag showing if the last message if from or to userid=12.
Thanks in advance for your help, i'm really blocked :(
Haven't tried it ;-) But maybe the right way to go.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.