Skip to content
Advertisement

Merge Two JSON array columns in Mysql 8

I am using Mysql (version > 8).

I have a table where I am storing unique customer ids for the day in an JSON field as an array.

I need to query for all unique customers in last 30 days. I am unable to find an equivalent mysql query for the same.

I am using JSON_ARRAYAGG to first merge all the arrays and then I am using ruby to flatten the array and find uniq values.

Example Query:

Advertisement

Answer

You can use json_table() to unnest the arrays as rows, and then json_arrayagg() to aggregate back:

If there are duplicate customer ids across arrays, and you want distinct values in the resultset, then you need an additional level of aggregation (since, unfortunately, json_arrayagg() does not support distinct):

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement