I have the following models in a Rails 3 app, and select requirement:
class Item < AR
has_many :holdings
class Holding < AR
belongs_to :item
The Holding model has an ‘active’ boolean value.
I wish to find each Item that has 0 ‘active’ holdings ( it may have any number of associated holdings ), I’ve tried quite a few combinations.
SELECT * from items JOIN
(SELECT holdings.item_id, count(ifnull(item_id,0)) AS hcount FROM holdings
WHERE holdings.active = "t"
GROUP BY holdings.item_id
HAVING hcount = 0)
ON items.id = holdings.item_id
but this will only return counts that are greater than 0.
Can anyone point me in the right direction?
Don’t use count when you mean any!
Use an not exists clause.
This statement in english says give me all the rows from items where there are no matching rows in holdings.