2010-11-21 100 views
0

我有在Rails 3應用以下型號,並選擇要求:SQL聚合計數= 0

class Item < AR
has_many :holdings

class Holding < AR
belongs_to :item

中的持有模型有一個 '有效' 的布爾值。

我希望找到每個擁有0個「活躍」持有的項目(它可能有任何數量的關聯持股),我嘗試了很多組合。

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

但這隻會返回那些大於0的

任何人都可以點我在正確的方向計數?

回答

1

當你的意思是任何!

使用不存在的子句。

SELECT * from items i 
where not exists(select holdings.item_id 
      from holdings 
      where holdings.active = 't' 
       and holdings.item_id = i.item_id) 

在英語中的這種說法說,給我所有的行中沒有配套的行中的行。

+0

謝謝,這使得更多的意義! – scaney 2010-11-21 23:47:21