49

I'm trying to achieve exactly what's explained here: Creating a threaded private messaging system like facebook and gmail, however i don't completly understand Joel Brown's answer. can any one please explain.

This is what my db tables look like with sample data (I assume i filled it in correctly for demo purposes): enter image description here

  1. I need to display a list of threads based on LoginId (newest on top) what would the query look like in LINQ? (what i'm asking is in a a group of message threads, give me the 1 newest message in each thread) - just like this is done on facebook.

  2. I need to display ALL the messages in a message thread (LINQ) -> just like it's done on facebook where you click the message and you would see the whole "conversation" in a tread.

Please help! thanks

EDIT -> continuation Joel, is this correct??

enter image description here

Joel, i'm a bit confused, can you please explain (comments/questions in bold):

The idea here is that every time a user starts a brand new thread/message, it starts with a new record in the THREAD table. The user is then added as a THREAD_PARTICIPANT and the content of the message is added to MESSAGE which points back to the containing THREAD. The FK from MESSAGE to USER indicates the author of the message.

LoginId 1 sends a message to LoginId2 => new record is inserted to MessageThread table. Also a record is inserted to MessageThreadParticipant record with MessageThreadId = 1, LoginId = 1 (the sender). And a new record is inserted into Message table with MessageId =1, MessageThreadid =1, SenderLoginId = 1 (correct??)

this is what i have after that iteration: enter image description here

I think i'm confused because there is no way for Loginid 2 to know that there is a message for him. ?? OR maybe I need to insert 2 records into MessageThreadParticipant?? (the sender and the receiver)-> this way both can see the whole "conversation"??

EDIT2: Joe, I think I could do this:

SELECT
  Message.MessageId, Message.CreateDate, Message.Body, Login.Username, Message.SenderLoginId
, (SELECT MessageReadState.ReadDate 
   FROM MessageReadState 
   WHERE MessageReadState.MessageId = Message.MessageId 
     ) as ReadDate
FROM Message 
    INNER JOIN Login ON Message.SenderLoginId = Login.LoginId
    INNER JOIN MessageThreadParticipant mtp on mtp.MessageThreadId = Message.MessageThreadId 
AND ( Message.MessageId in 
        ( SELECT Max(Message.MessageId)
          FROM MessageThreadParticipant INNER JOIN Message 
            ON MessageThreadParticipant.MessageThreadId = Message.MessageThreadId
          GROUP BY MessageThreadParticipant.MessageThreadId
        )
      )
Where mtp.LoginId = 2
ORDER BY Message.CreateDate DESC;

Please correct me if i'm wrong :)

2
  • Shane, I think you've got it. Have a look at my edited answer for expanded example data.
    – Joel Brown
    Jul 1, 2011 at 11:46
  • 1
    Shane, I don't think you can get it to work using your query from Edit 2. There are two issues that I see. One is that you will only see messages that are read by the user in question, since you're inner joining to MTP. The other is that you are trying to do a sub-select in your FROM (...Message.MessageId in ( SELECT Max(Message.MessageId) ...) which is highly unconventional, if it works at all, which I don't think it will because you can't join to a multi-valued equality. The sub-select belongs in a WHERE clause.
    – Joel Brown
    Jul 4, 2011 at 11:22

2 Answers 2

90

Well why don't you just ask? :)

Let me try to pin down my understanding of your requirement. It seems to me that you are looking at a thread being a linear list (not a tree) of messages between two people. I would think that you might want to allow more people in than just two. That would be like Facebook insofar as someone posts a message and then any number of people can read it and then start adding comments. When you add a comment it puts you into the thread and you start getting status updates and e-mails telling you about activity in the thread and so forth. Assuming that is what you're after, then the schema I suggested to Big Mike is not exactly what you're looking for.

Consider instead the following:

Schema

The idea here is that every time a user starts a brand new thread/message, it starts with a new record in the THREAD table. The user is then added as a THREAD_PARTICIPANT and the content of the message is added to MESSAGE which points back to the containing THREAD. The FK from MESSAGE to USER indicates the author of the message.

When a user reads a message, they get an entry in the MESSAGE_READ_STATE table to indicate that they have marked the message read, either explicitly or implicitly, depending on how your requirements go.

When someone comments on the initial message in the thread, a second MESSAGE is added with an FK back to the original THREAD and the reply author (user) gets added to the THREAD_PARTICIPANT table. And so it goes as messages are added to the thread by one, two or even more participants.

To get the most recent message in any thread, just take the top 1 from MESSAGE sorted descending on create date (or an identity key) where the message FK is to the thread of interest.

To get the most recently updated thread for a user, get the THREAD related to the top 1 from message sorted descending on create date where the message is in a thread in which the user is a THREAD_PARTICIPANT.

I'm afraid I can never state these things in LINQ without breaking out LinqPad. If you are having trouble catching my drift from the above, I could flesh out the answer with table definitions and some SQL. Just ask in the comments.

EDIT: Clarification of Requirements and Implementation

Clarifying the requirements: Initially I was thinking about publicly posted messages with the opportunity for commenting, whereas Shane is after more of the direct message feature. In which case the initial recipient needs to be included in the THREAD_PARTICIPANT table at the outset.

For some clarity, let's put a few rows in tables. Here is the scenario, (in honour of Canada Day): User 1 DMs User 2 to ask about meeting for a beer. User 2 replies with a question about where to meet and User 1 answers. The tables would look something like this: (probably oversimplified)

Sample Data Part 1 Sample Data Part 2

EDIT #2: Access SQL for list of all messages in a thread, with read state...

Using @OP's schema, this SQL will get a list of messages in a given thread with an indication of whether a given user has read each message or not. Messages are in most recent first order.

SELECT 
  Message.MessageId
, Message.CreateDate
, Message.Body
, Login.Username
, (SELECT MessageReadState.ReadDate 
   FROM MessageReadState 
   WHERE MessageReadState.MessageId = Message.MessageId 
     and MessageReadState.LoginId = 2) as ReadState
FROM (Message INNER JOIN Login ON Message.SenderLoginId = Login.LoginId) 
WHERE (((Message.MessageThreadId)=10))
ORDER BY Message.CreateDate DESC;

Note that the trick, if it's fair to call it that, is that the read state is picked up with a sub-select. This is necessary because part of the criteria for getting the read state requires a where clause that can't be satisfied with an outer join. Therefore you use the subselect to pin down which (possibly missing) value you want from the MessageReadState child table.

EDIT 3: SQL for getting all threads with latest message in each for a given user...

To get a list of all of the threads in which a given user has participated, sorted by most recent message first, with only the most recent message being displayed (1 message per thread) then you would use a similar query to the one above, except instead of filtering messages by their FK to the thread of interest, you filter the messages by a subquery that finds the latest message in each thread that the user of interest participated in. It would look like this:

SELECT
  Message.MessageId
, Message.CreateDate
, Message.Body
, Login.Username
, (SELECT MessageReadState.ReadDate 
   FROM MessageReadState 
   WHERE MessageReadState.MessageId = Message.MessageId 
     and MessageReadState.LoginId = 2) AS ReadState
FROM Message INNER JOIN Login ON Message.SenderLoginId = Login.LoginId
WHERE ( Message.MessageId in 
        ( SELECT Max(Message.MessageId)
          FROM MessageThreadParticipant INNER JOIN Message 
            ON MessageThreadParticipant.MessageThreadId = Message.MessageThreadId
          WHERE MessageThreadParticipant.LoginId=2
          GROUP BY MessageThreadParticipant.MessageThreadId
        )
      )
ORDER BY Message.CreateDate DESC;
34
  • 3
    @Spock - OP's requirements didn't say anything about users deleting messages, but the model can be easily enhanced to accomodate individual users choosing to "delete" a message while leaving the message there for other users to view. This could be done at the thread level by deleting the THREAD_PARTICIPANT record for that user or at the message level by adding a code or flag to MESSAGE_READ_STATE to indicate that the user has soft-deleted the message.
    – Joel Brown
    Jun 30, 2012 at 12:08
  • 2
    @user1066133 - I think code first has its place, especially as a prototyping tool or for building small or niche systems. I personally feel that code first was a concession to some programmers who aren't data-centric. In my experience, a very well considered (i.e. deliberately designed) database is a strong foundation for an application of any size or importance. If your project allows it, I would start with model first. If you have to work code first, you just have to make sure that you don't paint yourself into a very bad corner by skipping the data design step.
    – Joel Brown
    Jun 30, 2012 at 17:53
  • 2
    @compguy24 the usual way to exclude something based on information being missing is to use a sub-select with WHERE NOT IN .... So for example you could take the base query and add to its where clause AND WHERE Message.MessageID NOT IN ({select clause that pulls out the message ids of the thing that you're waiting for})
    – Joel Brown
    Feb 7, 2014 at 21:57
  • 2
    @DaveHarding - Yes, if you wanted to distinguish between message read and message deleted, you could expand the MESSAGE_READ_STATE table to include either a deleted flag or, perhaps preferably, a deleted date. This would provide a soft-delete feature (so that you can undelete if you want to) and it allows one participant in a thread to hide something without disrupting the data of other thread participants.
    – Joel Brown
    Nov 10, 2015 at 14:23
  • 1
    How to check weather a thread is already exist between 2 users, suppose a thread id=10 already exist for user 1 and user 2 so no need to create a new thread. Feb 7, 2016 at 17:57
3

According to Joel Brown'answer, you can add LAST_MESSAGE_ID column into THREAD table then getting all threads with last messages SQL is become very simple. You must update this column when every message send.

Getting all threads with latest message in each for a given user

SELECT *
FROM THREAD T
INNER JOIN MESSAGE M ON T.LAST_MESSAGE_ID=M.MESSAGE_ID
INNER JOIN USER SENDER ON M.USER_ID=SENDER.USER_ID
LEFT JOIN MessageReadState MRS ON M.MESSAGE_ID=MRS.MESSAGE_ID AND MRS.USER_ID=2
4
  • how to get thread_id for given two users ? do i need this sort of query -SELECT * FROM message_thread_has_user as t1 join message_thread_has_user as t2 on t1.message_thread_id=t2.message_thread_id where (t1.user_id = 1 || t2.user_id = 1) and (t1.user_id = 2 || t2.user_id = 2) group by t1.message_thread_id
    – vivex
    Jun 20, 2016 at 9:00
  • 1
    @Vivek you should add a unique char field = "unique_field" in MessageThread table . It stores users ids which ordered from min user id to max user id and joined with a seperator. example : user1=15, user2=9 and unique_field will be "9_15" and sql will be select * from MessageThread where unique_field="9_15"
    – Alexander
    Jun 20, 2016 at 12:37
  • @Alaxander that does make sense , this will avoid joins. thanks.
    – vivex
    Jun 20, 2016 at 19:00
  • @Vivek you can also use ThreadName field instead of creating "unique_field" for one to one message threads
    – Alexander
    Jun 21, 2016 at 5:07

Not the answer you're looking for? Browse other questions tagged or ask your own question.