ruby-on-rails - Rails Postgres - Jsonb 列查询
问题描述
我有一个带有名为“available_quantity”的 jsonb 列的捆绑表。这将有样本值
[{“面额”:“100”,“数量”:“20”},{“面额”:“1000”,“数量”:“19”}]
现在,我想查询所有数量小于 50 的记录。
我试过这个查询,
Bundle.where("(available_quantity->>'quantity')::numeric < 50")
但是这返回空的关系。
我怎样才能做到这一点?
架构
Table "offer_service.bundles"
Column | Type | Collation |
Nullable | Default
-----------------------+-----------------------------+-----------+----
------+--------------------------------------------------------
id | bigint | | not
null | nextval('offer_service.bundles_id_seq'::regclass)
project_id | bigint | |
|
item_type | character varying | |
|
item_id | bigint | |
|
status | integer | | not
null | 0
created_at | timestamp without time zone | | not
null |
updated_at | timestamp without time zone | | not
null |
denomination_quantity | jsonb | |
|
deleted_at | timestamp without time zone | |
|
available_quantity | jsonb | |
|
示例数据:
id: 2586, project_id: 3, item_type: "GiftCard", item_id: 659, status:
"activated", created_at: "2020-05-18 09:38:54", updated_at: "2020-05-
28 13:25:29", denomination_quantity: {"100"=>200, "1000"=>200},
deleted_at: nil, available_quantity: [{"quantity"=>16,
"denomination"=>"100"}, {"quantity"=>20, "denomination"=>1000}]
解决方案
希望我们必须在这里使用子查询。
Bundle.select("*").from(Bundle.select("*, jsonb_array_elements(available_quantity) as aq")).where("(aq ->> 'quantity')::numeric <= 50").distinct
欢迎提出重构上述查询的建议!
推荐阅读
- c# - 数据访问类设计:使类可测试,同时还包含依赖项
- python - Linux:来自图像命令工作的 FFMPEG 延时视频仅在目录中的 1000 个图像中收集几个图像 提前终止
- java - 如何使用更新和删除按钮更新和删除 JTable 和文本文件中的数据?
- insert - 使用 Sublime Text 在覆盖/插入模式下粘贴
- php - 使用 fit_transform 和 transform 缩放训练集和测试集(StandardScaler、Binarizer)的数据集
- java - 'parallelStream' 函数的性能是否因原子变量而降低?
- typescript - 打字稿中的 is 语句有什么作用?
- c# - HasPrincipalKey() 等效于实体框架 6?
- visual-studio-code - 在 VSCode 中为 Material Theme 更改选择器的颜色
- django - 在 ECS 中为 Celery 部署策略