首页 > 解决方案 > Rails - 获取结果为 0 以获得 DB 中不存在的值

问题描述

我正在使用此查询来获取带有价格的产品。

select sku, price from products where sku in ('001', '002', '003');

预期结果:

{
  '001': 50,
  '002': 40,
  '003' : 0 // if the sku doesn't exit, want to set price 0
}

但是上面的查询只返回数据库中存在的产品,所以我需要循环结果,如果结果中不存在产品,则添加 0。

有什么方法可以在不循环 Rails 或 PostgreSQL 的情况下获得预期的结果?

标签: ruby-on-railsrubypostgresql

解决方案


构建目标 sku-s(tCTE)的列表并将其与products. 用于string_to_array构建列表以使查询适合参数化。

-- '001,002,003' is the list of products to query
with t(sku) as 
(
 select unnest(string_to_array('001,002,003', ','))
)
select json_object_agg(t.sku, coalesce(p.price, 0))
from t 
left outer join products p on t.sku = p.sku;

SQL小提琴

参数化和无 CTE:

select json_object_agg(t.sku, coalesce(p.price, 0))
from unnest(string_to_array(?, ',')) t(sku)
left outer join products p on t.sku = p.sku;

推荐阅读