来自 sqlite3 文档
select json_insert('{"a":2,"c":4}', '$.e', 99) -- → '{"a":2,"c":4,"e":99}'
但是如何将新元素附加到数组中?
select json_insert('[1,2,3]', ??, 4) -- → '[1, 2, 3, 4]'
update someTable set someArray = json_insert(someArray, ??, 'some new value')
来自 sqlite3 文档
select json_insert('{"a":2,"c":4}', '$.e', 99) -- → '{"a":2,"c":4,"e":99}'
但是如何将新元素附加到数组中?
select json_insert('[1,2,3]', ??, 4) -- → '[1, 2, 3, 4]'
update someTable set someArray = json_insert(someArray, ??, 'some new value')
经过几次尝试,我终于想通了
update some_table
set some_array = json_insert(
some_array,
'$[' || json_array_length(some_array) || ']',
'new item'
)
where id = some_id;
显然没有功能或简单的方法可以做到这一点,但我们可以通过以下方式实现:
json_each
UNION ALL
GROUP BY
json_group_array
例如,如果您有一个Messages
包含 PRIMARY KEY 的表id
和一个 JSON 数组 in account
,您可以在所有行中向 account 数组中添加一个元素:
SELECT id, json_group_array(value) FROM (
SELECT Messages.id, json_each.value
FROM Messages, json_each(Messages.account)
UNION ALL SELECT Messages.id, 'new_account' FROM Messages
) GROUP BY id;
我们需要再次包装以放入 aUPDATE
因为 SQLite 不支持UPDATE
+ JOIN
。这会将新帐户添加到所有行:
UPDATE Messages SET account = (SELECT account FROM (
SELECT id, json_group_array(value) as account FROM (
SELECT Messages.id, json_each.value
FROM Messages, json_each(Messages.account)
UNION ALL SELECT Messages.id, 'new_account' FROM Messages
) GROUP BY id
) WHERE id = Messages.id);
如果您只想像这样更新一行,我们可以简化这一点:
UPDATE Messages SET account = (
SELECT json_group_array(value) FROM (
SELECT json_each.value
FROM Messages, json_each(Messages.account)
WHERE Messages.id = 123456789
UNION ALL SELECT 'new_account'
) GROUP BY ''
) WHERE id = 123456789;
在3.31.0版本中引入了一个新的符号来直接支持这个功能:
select json_insert('[1,2,3]', '$[#]', 4) -- → '[1, 2, 3, 4]'