-2

I'm trying to extract values from Array in JSON object, get the most repeated values and order it.

My column tags have next object: {"en":["polytics","friendly"]}

For example: I have many rows with this data, the object "en" have an array with many values, and I'm trying to extract from all rows the array values and order it by most repeated.

How is the sql query? Any help? Thanks.

El Tito Barte
  • 277
  • 2
  • 13

1 Answers1

1

Since you are using MySQL 5.7, you don't have support for the JSON_TABLE() function, which would be the solution for the query you describe.

SELECT j.tag, COUNT(*) AS count
FROM mytable CROSS JOIN 
JSON_TABLE(tags, '$.en[*]' COLUMNS(tag VARCHAR(10) PATH '$.') AS j
GROUP BY j.tag
ORDER BY count DESC;

I would strongly recommend that you store your multi-valued data in normal columns and rows, not in JSON. Then the query would become more straightforward:

SELECT `tag`, COUNT(*) AS count
FROM en_tags
GROUP BY `tag`
ORDER BY count DESC;
Bill Karwin
  • 538,548
  • 86
  • 673
  • 828