I’ve inherited a system using SQL Server (2008 R2) with two tables that cover system messaging. A message has a one to many relationship, it can be sent to multiple users.
Primary table, Messaging, looks like:
Id (PK, auto increment)
Subject
MessageBody
CreatorEmployeeId
ConversationId
IsConversationStarter (bool)
Secondary table, MessagingDetails, looks like:
ID (PK, auto increment)
MessageId (FK to Messaging PK)
RecipientEmployeeId
ConversationId
IsRead (bool)
If that’s not clear, a new message is put into the Messaging table with an employee Id for who created the message, and new Conversation Id is created. Then X number of rows will be inserted into MessagingDetails, one per recipient, with references back to the Messaging table and using the same Conversation Id.
Any new replies will look the same, reply message goes into the Messaging table, recipient details go into MessagingDetails using the same Conversation Id, so that you can pull a whole message thread by one number.
This gets sloppy when you’re trying to get a count of all unread messages that you’ve created or that have been sent to you. Here’s an existing query that gets all of the unread messages sent to the logged-in user by other users in the system, where they created the message originally:
SELECT * FROM dbo.Messaging m
INNER JOIN dbo.MessagingDetails m1 on m.Id = m1.MessageId
INNER JOIN dbo.MessagingDetails m2 on m1.ConversationId = m2.ConversationId
WHERE m1.RecipientEmployeeId = @employeeId
AND m.IsConversationStarter = 1
AND m.ConversationId = m1.ConversationId
AND m2.IsRead = 0
AND m2.RecipientEmployeeId == @employeeId
Then to find all messages that the employee created but have unread replies, you have to do an almost identical query, swapping out the first part of the WHERE clause for:
m.CreatorEmployeeId = @employeeId
I loathe the inner joining the same table twice, once to itself. Given that schema outlined above, is there a better way to write these queries?
For “messages send by employee that have unsent replies”, I think this solves the problem:
I’m not sure what information you want about the message. This just gives the message id.
The same approach works for all messages sent to users by others:
Your description and your question don’t mention conversionid. Is this relevant?