I have a conversation table, and a user conversation table.
CONVERSATION
Id, Subject, Type
USERCONVERSATION
Id, UserId, ConversationId
I need to do a SQL Query based on a list of UserIds. So, if I have three UserIds for the same ConversationId, I need to perform a query where if I provide the same three userIds, it will return the ConversationId where they match exactly.
Assuming the same user can’t be in a UserConversation twice:
This also works:
If you find that performance is poor with either of these queries then a two-step method could help: First find all conversations containing at least the desired parties, then from that set exclude those that contain any others. Indexes of course will make a big difference.
Getting rid of the ID column from UserConversation will improve performance by getting more rows per page, thus more data per read (about 50% more!). If your Id column is not only the PK but also the clustered index, then immediately go change the clustered index to
ConversationId, UserId(or vice versa, depending on the most common usage)!If you need help with performance post a comment and I’ll try to help you.
P.S. Here’s another wild idea but it may not perform as well (though things can surprise you sometimes):