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;