0

我在 Rails 3 应用程序中有以下模型,并选择要求:

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 的计数。

谁能指出我正确的方向?

4

1 回答 1

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)

这条英文声明说给我所有馆藏中没有匹配行的项目的所有行。

于 2010-11-21T23:37:16.273 回答