3

Is there a JSON function in mysql that will ignore trying to add the element if it already exists? For example:

update waitinglist SET
new = JSON_ARRAY_APPEND(new, '$', "orange")
where id=2;

update waitinglist SET
new = JSON_ARRAY_APPEND(new, '$', "orange")
where id=2;

Now my array looks like:

["apple", "orange", "orange", "orange", "orange"]

But I want it to work like a set, and just be:

["apple", "orange"]

Is there a way to do this?

4

1 回答 1

6

我不这么认为。WHERE您可以在子句中测试该值是否已经在 J​​SON 中。

update waitinglist SET
new = JSON_ARRAY_APPEND(new, '$', '"orange"'))
where id=2
AND NOT JSON_CONTAINS(new, '"orange"')

如果您要更新多列并且需要它只影响这一列,IF()如果值已经存在,您可以使用它保持不变。

update waitinglist SET
new = IF(JSON_CONTAINS(new, '"orange"'), new, JSON_ARRAY_APPEND(new, '$', '"orange"'))
where id=2
于 2018-12-08T00:22:13.250 回答