比较Postgres中的JSON数组

时间:2017-04-06 12:01:36

标签: sql postgresql

我有一张表,表示不同时刻购物车中的商品。购物车商品以JSON格式存储,一列包含before值,另一列包含after值。

我的任务是比较购物车并确定:添加的商品,已移除的商品以及价格/数量的变化。

我知道我可以使用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;

1 个答案:

答案 0 :(得分:2)

你可以使用except all来区分你的两个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)