2010-11-21 22 views
0

は: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

何時でもカウントを使用しないでください!

not exists句を使用します。英語で

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