6

I have a table with a json column that looks like this :

+----+------------+
| id | myfield    |
+----+------------+
|  1 | ["1", "2"] |
|  2 | ["3", "2"] |
|  3 | ["2", "4"] |
+----+------------+

How can I merge all values from myfield in one array?

I need a result that will look like this: ["1", "2", "3", "2", "2", "4"], or even better with removed duplicates.

I tried using this query: SELECT JSON_ARRAYAGG(myfield) FROM json_test but as a result I'm getting:

[["1", "2"], ["3", "2"], ["2", "4"]]

I assume I need a query in combination with the function JSON_MERGE.

2
  • What does SELECT @@version; return? The best answer could depend on which exact version of MySQL you are using. Commented Feb 15, 2021 at 21:41
  • @BillKarwin 5.7.22, but I'm open to upgrading to any needed version as I'm at the project's beginning. Commented Feb 15, 2021 at 22:15

1 Answer 1

8

Here's a solution but it requires MySQL 8.0 for the JSON_TABLE() function:

SELECT GROUP_CONCAT(j.myvalue) AS flattened_values
FROM mytable, JSON_TABLE(
  mytable.myfield, '$[*]' COLUMNS(myvalue INT PATH '$')
) AS j;

Output:

+------------------+
| flattened_values |
+------------------+
| 1,2,3,2,2,4      |
+------------------+

I would actually recommend avoiding storing JSON arrays. Instead, store multi-valued data in a normalized manner, in a second table. Then you could just use GROUP_CONCAT() on the joined table.

I have still yet to hear of a use of JSON in MySQL that isn't better accomplished by using database normalization.

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

2 Comments

I expected a simpler solution since MySQL officially supports JSON operations, but anyway, thanks for the answer.
This is MySQL's solution for JSON operations. All use of JSON is done through a variety of JSON functions, which are still evolving. This makes an old-school normalized database seem pretty good doesn't it?

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.