2017-04-06 77 views
2

我有一个表格表示不同时刻购物车中的物品。购物车商品以JSON格式存储,其中一列的值为before,另一列的值为after比较Postgres中的JSON数组

我的任务是比较购物车和识别:添加的项目,删除的项目和价格/数量的变化。

我知道我可以使用json_array_elements和一个交叉连接来解开JSON blob,从JSON值创建一个项目表。但我想不出一种比较购物车物品的有效方法。我可以在SQL中执行此操作吗?

这里是一个小例子SQL Fiddle

CREATE TABLE t (
    id  INT, 
    before JSON, 
    after JSON 
); 

INSERT INTO t VALUES (
    1, 
    '[{"category":"item","id":"1","price":8,"quantity":1},{"category":"item","id":"2","price":20,"quantity":1},{"category":"item","id":"3","price":3,"quantity":1}]', 
    '[{"category":"item","id":"2","price":40,"quantity":1},{"category":"item","id":"3","price":3,"quantity":1},{"category":"item","id":"4","price":2,"quantity":1}]' 
); 

这种昂贵查询不解决我的问题:

select 
    id, 
    b.value->>'id' as id_before, 
    b.value->>'category' as category_before, 
    b.value->>'price' as price_before, 
    b.value->>'quantity' as quantity_before, 
    a.value->>'id' as id_after, 
    a.value->>'category' as category_after, 
    a.value->>'price' as price_after, 
    a.value->>'quantity' as quantity_after 
from t 
CROSS JOIN json_array_elements(before) b 
CROSS JOIN json_array_elements(after) a; 

回答

2

可以使用除了所有让你的两个JSON之间的差异,通过这可以得到哪个项目被添加和删除。 为了找到差异我的查询将是:

select 
value->>'id', 
value->>'category', 
value->>'price', 
value->>'quantity' 
FROM 
    json_array_elements(before) 
EXCEPT ALL 
select 
value->>'id', 
value->>'category', 
value->>'price', 
value->>'quantity' 
FROM 
    json_array_elements(after)