我需要编写一个始终返回整数值的方法。如果记录不存在,则该方法返回 0
我在被查询的列上有一个唯一索引,并提出了两个解决方案:
# Option a) Ruby logic
def some_method id
result = Model.some_scope.find(:first,
conditions: { foo_id: id },
select: :int_value)
# Return 0 if record does not exist:
( result.nil? ? 0 : result.int_value )
end
# Option b) Allow Postgres to do the work
def some_method id
# sum() returns 0 if the record wasn't found
Model.some_scope.where(foo_id: id).sum(:int_value)
end
由于唯一索引,两种方法返回相同的值。
除了简洁之外,是否有任何理由表明一种解决方案优于另一种解决方案?
我倾向于选择基于服务器资源的解决方案,即通过将工作交给 Ruby 来最小化数据库服务器负载。
运行 Ruby 1.9.3 和 Postgres 9.1
最佳答案
您不需要(可能更昂贵的)聚合函数 sum()
。
使用 SQL- COALESCE()
为此。
COALESCE
可能是最便宜的方式。但成本是如此之小,无论哪种方式都没有关系。
关于ruby - 什么是更聪明的选择 : Ruby logic or SQL function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10609372/