5

Is it possible to remove an element by its value (and not its index) in a json array in mysql? For example:

# ['new', 'orange']
update waitinglist SET new = JSON_REMOVE("orange", '$') WHERE id=2;
# now it will be ['new']

If not, is there a better way to store this, so I can remove elements as needed? Also, there would never be duplicates in the array.

4

2 回答 2

9

如果您知道数组中从不重复,您可以使用JSON_SEARCH找到要删除的值的路径,然后使用JSON_REMOVE将其删除。请注意,您需要检查是否JSON_SEARCH实际找到了一个值,否则JSON_REMOVE将使整个字段无效:

UPDATE waitinglist 
SET new = JSON_REMOVE(new, JSON_UNQUOTE(JSON_SEARCH(new, 'one', 'orange')))
WHERE JSON_SEARCH(new, 'one', 'orange') IS NOT NULL

在 dbfiddle 上做了一个小演示

请注意,您必须使用JSON_UNQUOTE来自的响应JSON_SEARCH以使其成为JSON_REMOVE.

于 2018-12-08T00:06:51.797 回答
1

这里有点不同的方法,但它允许一次从 json 数组中删除多个值。我正在使用子查询来获取正确的数组值,然后只更新 json 字段。因此,在您的情况下,sql 查询将如下所示:

UPDATE waitinglist w
SET w.new =
        (
            SELECT JSON_ARRAYAGG(new)
            FROM JSON_TABLE(w.new, '$[*]' COLUMNS (new VARCHAR(255) PATH '$')) AS list
            WHERE list.new NOT IN ('orange')
        )
WHERE w.id = 2;

要从 json 数组中删除的值必须NOT IN在子查询的子句中指定。

于 2021-07-27T16:43:58.150 回答