Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails group/having/count query

Given a situation like: Company has_many Users

To get the Companies that have 3 Users, this works efficiently:

Company.joins(:users).group("companies.id").having("COUNT(users.id)=3")

But what's the most efficient way to get the Companies that have 0 Users (none)? Because, obviously, the same approach would not work (as joins by definition excludes Companies with 0 Users):

Company.joins(:users).group("companies.id").having("COUNT(users.id)=0")
like image 289
TomDogg Avatar asked May 06 '14 11:05

TomDogg


1 Answers

Do a LEFT JOIN instead of INNER JOIN.

Company.joins('LEFT OUTER JOIN users ON companies.id = users.company_id')
like image 94
Lenin Raj Rajasekaran Avatar answered Nov 03 '22 17:11

Lenin Raj Rajasekaran