简体   繁体   English

Postgres从JSONB更新INTEGER列

[英]Postgres update INTEGER column from JSONB

I have a table cart : 我有桌子cart

 id     | value |     metadata
--------+-------+-------------------
  45417 |     0 | {"value": "1300"}
  45418 |     0 | {"value": "1300"}
 276021 |     0 | {"value": "1300"}

and I'm trying to UPDATE the value column with the value in the JSONB metadata if it exists. 并且我正在尝试使用JSONB metadata的值更新value列(如果存在)。 I come up with the following query: 我提出以下查询:

UPDATE cart SET value=CAST(subquery.meta_val as INTEGER) FROM
(SELECT id, metadata->>'value' as meta_val FROM cart
WHERE value = 0 AND 
metadata->>'value' IS NOT NULL) as subquery
WHERE cart.id=subquery.id;

Now this works but it takes quite a lot of time for 4M rows I want to update on production and it looks to me like there is a lot of redundancy in the query. 现在可以正常工作,但是要在生产中更新4M行需要花费大量时间,而且在我看来查询中存在很多冗余。

I think the next step would be to wrap all this in a transaction and improve the query, is there anything that can be done to improve performance out of this query ? 我认为下一步是将所有内容包装在事务中并改进查询,是否可以做些改进以提高此查询的性能?

Try it without a subquery. 尝试不带子查询的情况。

update cart as c
set value = coalesce((c.metadata->>'value')::int, 0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM