2016-08-23 53 views
2

說我有以下產品模式,它具有常用屬性(如標題等)以及數組中的變體。Postgres按價格從低到高依次使用jsonb數組

我會如何按照價格從低到高排列產品?

drop table if exists product; 

create table product (
    id int, 
    data jsonb 
); 

insert into product values (1, ' 
{ 
    "product_id": 10000, 
    "title": "product 10000", 
    "variants": [ 
    { 
     "variantId": 100, 
     "price": 9.95, 
     "sku": 100, 
     "weight": 388 
    }, 
    { 
     "variantId": 101, 
     "price": 19.95, 
     "sku": 101, 
     "weight": 788 
    } 
    ] 
}'); 

insert into product values (2, ' 
{ 
    "product_id": 10001, 
    "title": "product 10001", 
    "variants": [ 
    { 
     "variantId": 200, 
     "price": 89.95, 
     "sku": 200, 
     "weight": 11 
    }, 
    { 
     "variantId": 201, 
     "price": 99.95, 
     "sku": 201, 
     "weight": 22 
    } 
    ] 
}'); 

insert into product values (3, ' 
{ 
    "product_id": 10002, 
    "title": "product 10002", 
    "variants": [ 
    { 
     "variantId": 300, 
     "price": 1.00, 
     "sku": 300, 
     "weight": 36 
    } 
    ] 
}'); 


select * from product; 

1;"{"title": "product 10000", "variants": [{"sku": 100, "price": 9.95, "weight": 388, "variantId": 100}, {"sku": 101, "price": 19.95, "weight": 788, "variantId": 101}], "product_id": 10000}" 
2;"{"title": "product 10001", "variants": [{"sku": 200, "price": 89.95, "weight": 11, "variantId": 200}, {"sku": 201, "price": 99.95, "weight": 22, "variantId": 201}], "product_id": 10001}" 
3;"{"title": "product 10002", "variants": [{"sku": 300, "price": 1.00, "weight": 36, "variantId": 300}], "product_id": 10002}" 

回答

3

使用jsonb_array_elements()到UNNEST variants,例如:

select 
    id, data->'product_id' product_id, 
    var->'sku' as sku, var->'price' as price 
from 
    product, jsonb_array_elements(data->'variants') var 
order by 4; 

id | product_id | sku | price 
----+------------+-----+------- 
    3 | 10002  | 300 | 1.00 
    1 | 10000  | 100 | 9.95 
    1 | 10000  | 101 | 19.95 
    2 | 10001  | 200 | 89.95 
    2 | 10001  | 201 | 99.95 
(5 rows)  
+2

媽的,打:) – Phill

相關問題