ruby-on-rails - 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 的情况下获得预期的结果?
解决方案
构建目标 sku-s(t
CTE)的列表并将其与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;
参数化和无 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;
推荐阅读
- javascript - 在 Kotlin 的 WebView 的 JavascriptInterface 中执行页面的 JavaScript
- android - 当我点击 TextField 然后键盘打开但 TextField 没有在顶部颤动 Android 上滑动
- javascript - jQuery 函数不运行以显示“模态”元素
- ios - 通过 iOS 中的配置文件手动安装后,自签名证书不起作用
- django - Django模型双重反向查找2次导致重复,如何优化
- python - 将所有列除以熊猫中的每一列
- sql - 使用 Oracle SQL 获取 top 1 数据
- hash - 如何将哈希键添加到 Firebase OTP 短信正文部分
- rest-assured - 当post方法执行delete和put with payload时如何放心测试
- django - Django模板大数据分页链接问题