![](/img/trans.png)
[英]Is there any alternative of in operator in where clause for active record query in rails
[英]Rails 5 where or active record query
我正在嘗試編寫一個查詢來計算供應商組中特定 state 上的產品數量,如果沒有產品則返回 0。
如果產品存在,此查詢將僅返回計數。
SUPPLIER_GROUP_ATTRS = [
"id",
"count(products) as completed_products_count"
]
SupplierGroup.left_joins(:products).where("products.state=?","completed").select(SUPPLIER_GROUP_ATTRS).group(:id)
使用sum()
而不是count()
,然后select case
,這樣我們就可以忽略您的where
子句。
SUPPLIER_GROUP_ATTRS = [
"id",
"sum(case when products.state='completed' then 1 else 0 end) as completed_products_count"
]
SupplierGroup.left_joins(:products).select(SUPPLIER_GROUP_ATTRS).group(:id)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.