Let’s say I have two tables:
Member
------------------------
| user_id | first_name |
------------------------
Messages
--------------------------------------------------
| sender_id | recipient_id | message_type | body |
--------------------------------------------------
I’d like to create a query that returns:
---------------------------------------------
| user_id | first_name | number_of_messages |
---------------------------------------------
The number_of_messages should only count the messages of a certain type, message_type = 0, however I still want to include the members in the result set that didn’t send any messages of that type.
This is what I’ve got currently:
SELECT [user_id], [first_name], COUNT(sender_id) as number_of_messages
FROM [Member]
FULL OUTER JOIN [Message] ON user_id = sender_id
where message_type = 0
GROUP BY [Member].[user_id], [first_name]
ORDER BY number_of_messages DESC
The problem with this query is any member who hasn’t sent a message of type 0 will not be included in the result set. So I kind of want to use the message_type = 0 clause to reduce the number_of_messages, however I don’t want it to affect the number of results returned.
If there are any other optimizations I could make to my query that you see, please feel free to comment on them too.
Use an OUTER JOIN:
Note that my query includes the
message_typefilter in the JOIN criteria — NOT in the WHERE clause. Placement is important with OUTER join syntax — in the JOIN clause applies the criteria before the JOIN. WHERE criteria is applied after the JOIN, and can give different results.