0

I have a table with json columns with default empty arrays [].

old table

id myJson
A1 [1, 2]
A12 []

I want the table updated to below.

id myJson
A1 [1, 2, 321, 432]
A12 [222]

Tried - INSERT INTO table (id, myJson) VALUES ("A1", "[321, 432]"), ("A12", "[222]") ON DUPLICATE KEY UPDATE myJson = JSON_ARRAY_APPEND(myJson, "$", myJson)

Above query and other tried so far did not produce desirable result.

What query can i use to append new arrays to old as shown in the tables?

2

1 Answer 1

1

What version of MySQL are you using?

One option is to use JSON_MERGE_PRESERVE or JSON_MERGE_PATCH (as needed):

INSERT INTO `table` (`id`, `myJson`)
VALUES ('A1', '[321, 432]'), ('A12', '[222]') AS `new`
  ON DUPLICATE KEY UPDATE
    `table`.`myJson` = JSON_MERGE_PRESERVE(`table`.`myJson`, `new`.`myJson`);

See dbfiddle.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks. I Use version 8.0.28. It is producing error as I can't give alias to VALUES. Unexpected token. (near "AS" at position 94) Unrecognized statement type. (near "AS" at position 94)
@Dare: Are you executing the statement from the MySQL command line (CLI) or another client (PHPMyAdmin, for example)?
Executing from PHPMyAdmin, using XAMPP
This eventually worked on my PHPMyAdmin ` INSERT INTO table (id, myJson) VALUES ("A1", "[A321, 432]"), ("A12", "[222]") ON DUPLICATE KEY UPDATE myJson = JSON_MERGE_PRESERVE(myJson, VALUES(myJson)) `
@Dare: Possibly PHPMyAdmin has not yet implemented the change and therefore the error. See MySQL 8.0.20 - INSERT ... ON DUPLICATE KEY UPDATE statements is now deprecated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.