I have a table representing the items in a cart at different moments in time. The cart items are stored in JSON format, one column with the before values and another with the after values.
My tasks is compare the carts and identify: items added, items removed and price/quantity changes.
I know I can use json_array_elements and a cross join to unpack the JSON blobs, creating a table of items from the JSON values. But I can't think of an efficient way to compare cart items. Can I do this in SQL?
Here is a small example 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}]'
);
This expensive query does not solve my problem:
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;