首页 > 解决方案 > 如何通过在 sqlite 表中引用自身来更新 json 对象值?

问题描述

假设我有一个表features,其中有一列data包含 json 对象。

CREATE TABLE features ( id INTEGER PRIMARY KEY, data json )

现在,一个示例数据对象可能是:

{"A":
   {"B":
      {"coordinates":[
         {"x":1, "y":1},
         {"x":10, "y":10}
       ]
    }
}

现在我需要浏览此data列中的所有数据并将coordinates.

我尝试将其设置为自己的值除以 0.5,但这似乎适用于第一行,然后将所有其他行设置为完全相同的值。

update features
set data = 
(select json_set(features.data, "$.A.B.coordinates[0].x", (select json_extract(features.data, "$.A.B.coordinates[0].x")/0.5 from features))
from features);

我如何引用它自己的值json_set并为每一行重复?遍历每一行并将坐标加倍的最佳方法是什么?

标签: jsonsqlite

解决方案


没有必要SELECT声明。
您可以直接引用data同一行中列的值:

UPDATE features
SET data = json_set(
             features.data, 
             "$.A.B.coordinates[0].x", json_extract(features.data, "$.A.B.coordinates[0].x") * 2
           );

或者,如果要更新所有xs 和ys:

UPDATE features
SET data = json_set(
             features.data, 
             "$.A.B.coordinates[0].x", json_extract(features.data, "$.A.B.coordinates[0].x") * 2,
             "$.A.B.coordinates[0].y", json_extract(features.data, "$.A.B.coordinates[0].y") * 2,
             "$.A.B.coordinates[1].x", json_extract(features.data, "$.A.B.coordinates[1].x") * 2,
             "$.A.B.coordinates[1].y", json_extract(features.data, "$.A.B.coordinates[1].y") * 2
       );

演示


推荐阅读