我很难获得查询工作。查询返回重复的行。
手工计数与来自连接的计数:https://www.dropbox.com/s/sms6mot4ly6b54o/Screenshot%202014-05-09%2018.33.09.png - 第一个结果表示companies.products.count,第二个结果表示通过连接语句创建的计数。
@shopping_setups = ShoppingSetup.joins(:company).
joins("LEFT JOIN products on companies.id = products.company_id").
joins("LEFT JOIN categories on companies.id = categories.company_id").
select("shopping_setups.*").
select("COUNT(products.company_id) AS products_count").
select("COUNT(categories.company_id) AS categories_count").
group("shopping_setups.id, companies.id, products.company_id, categories.company_id")
class ShoppingSetup
belongs_to :company
end
class Company
has_one :shopping_setup
has_many :products
has_many :categories
end
class Product
belongs_to :company
end
class Category
belongs_to :company
end
编辑:问题是我做错了什么?为什么连接中的计数返回了这么多重复的行?