2013-05-15 31 views
0

嗨我試圖練習SQL,這是更多的控制檯使用不在我的實際模型。我有一個Collection型號has_many: products。我想要搜索所有超過15種產品的集合。Rails + find_by_sql:如何選擇產品數量超過15的集合?

這是我寫(並且是錯誤的):

Collection.find_by_sql("SELECT c.id FROM collections c WHERE count(product_id) > 15")

誰能幫助我嗎?由於

回答

0

你可以用一個子查詢做到這一點:

SELECT *, 
    (SELECT COUNT(*) FROM services WHERE collection_id = c.id) services_count 
FROM collections c WHERE services_count > 15 

你可以試試這個?我沒有測試它。

此外,還有一種方法可以在不使用普通SQL的情況下使用Active Record執行此操作,但我不記得如何執行此操作。

0

也許這個SQL查詢將幫助您

select collections.*, count(products.id) as count_products from collections 
inner join products on products.collection_id = collections.id 
having count_products > 15