简体   繁体   English

Rails Postgres - Jsonb 列查询

[英]Rails Postgres - Jsonb Column Query

I have a Bundle tabel with jsonb column named 'available_quantity'.我有一个带有名为“available_quantity”的 jsonb 列的捆绑表。 which will have sample values这将有样本值

[{ "denomination": "100", "quantity": "20"}, { "denomination": "1000", "quantity": "19"}] [{“面额”:“100”,“数量”:“20”},{“面额”:“1000”,“数量”:“19”}]

Now, I want to query all records with quantity less than 50.现在,我想查询所有数量小于 50 的记录。

I tried this query,我试过这个查询,

Bundle.where("(available_quantity->>'quantity')::numeric < 50") Bundle.where("(available_quantity->>'quantity')::numeric < 50")

But this return empty Relation.但是这返回空的关系。

How can I do that?我怎样才能做到这一点?

SCHEMA架构

                                            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                       |           |          
| 

Example Data:示例数据:

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}]

Hope we have to use sub query here.希望我们必须在这里使用子查询。

 Bundle.select("*").from(Bundle.select("*, jsonb_array_elements(available_quantity) as aq")).where("(aq ->> 'quantity')::numeric <= 50").distinct

Suggestions on refactoring the above query is welcomed!欢迎提出重构上述查询的建议!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM