You need to understand how left / right joins work.
For rows in the
usertype
table with no corresponding rows in the
users
table, all columns from the
users
table will be
NULL
.
Your
WHERE
clause will then remove those rows, since
YEAR(u.`userOn`)
will be
NULL
, and
u.`userRole`
will be
NULL
. Neither condition in your
WHERE
clause will match those rows.
Move your conditions to the
JOIN
clause instead.
NB: You've already specified the
roleId
match, so you don't need to specify that again.
SELECT COALESCE(COUNT(u.`userId`), 0) As 'Total', r.`roleName` As 'Role' FROM `users` u RIGHT JOIN `usertype` r ON u.`userRole` = r.`roleId` And YEAR(u.`userOn`) > 2011 GROUP BY r.`roleName`;
NB: The month and year columns do not make any sense. You're grouping the users by role name, so there could be multiple values for these columns. Which single value are you expecting to appear here? You will need to use an aggregate function to pick the correct one.