In this query:
SELECT COUNT(*) AS UserCount, Company.* FROM Company LEFT JOIN User ON User.CompanyId = Company.Id WHERE Company.CanAccessSystem= true AND(User.CanAccessSystem IS null OR User.CanAccessSystem = true) GROUP BY Company.Id
I want to query a list of companies that can access a particular system as well as the number of users who can access the system inside the company.
This query works for all cases except for one very important one. If a company can access a the system but none of the users can, the Company disappears completely from the query (i.e.: Users.CanAccessSystem = false). In that case, I just want the UserCount = 0.
Example From Companies that Can Access the System:
Users Company Name 1 WidgetWorks 3 WidgetCompany 0 WidgesRUs
This system is on MySQL
Query Edit: Fixed a Typo ‘ON User.CompanyId = Company.Id’
The reason that your result doesn’t work is because you don’t have any join clause.
That should work. The point with a left join is that the master table-entries should always appear, however left joined entries doesn’t have to.
the IFNULL() is only for returning 0 since no appropriate users will render a NULL-value in this case. I’m not really sure how you handle boolean values in MySQL since it doesn’t support it natively.