Skip to content
Advertisement

How to calculate count of each value in MySQL JSON array?

I have a MySQL table with the following definition:

The table has some sample data as follows:

How can I calculate the total number of occurrences for each fruit? For example:

Some research shows that the JSON_LENGTH function can be used but I cannot find an example similar to my scenario.

Advertisement

Answer

You can use JSON_EXTRACT() function to extract each value (“apple”, “mango”, “strawberry” and “orange”) of all three components of the arrays, and then then apply UNION ALL to combine all such queries:

Indeed If your DB’s version is 8, then you can also use JSON_TABLE() function :

Demo

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