MySQL join in a JSON array

扶醉桌前 提交于 2021-02-10 14:14:52

问题


I have these rows in mysql table

id  categoryNameSp    categoryNameEn
1   Comida            Food
2   Fruta             Fruit
3   Fruta Seca        Dried fruit

And then i have this row in another table

pid  path
1    ["1", "2", "3"]

I want to return the path but instead of numbers i want to return categoryNameEn so the return will be:

  pid  path
  1    ["Food","Fruit", "Dried fruit"]

回答1:


This would require to use the JSON_TABLE functionality as well as the JSON_ARRAYAGG aggregation function.

Recreating your situation using the following DML and DDL:

CREATE TABLE categories (id INT, name VARCHAR(30));
INSERT INTO categories VALUES (1, 'Food'), (2, 'Fruit'), (3, 'Dried Fruit');

CREATE TABLE stuff (pid INT, path JSON);
INSERT INTO stuff VALUES (1, '["1", "2", "3"]');

Then we can do the following (fancy) query:

SELECT pid, JSON_ARRAYAGG(c.name) FROM stuff AS s
    JOIN JSON_TABLE(s.path, '$[*]' COLUMNS (category INT PATH '$')) AS cats
    JOIN categories AS c ON cats.category = c.id
    GROUP BY pid;

The idea is to create a table from the JSON data found in the stuff table. We then join it with the categories tables, and aggregate the result into a JSON array.

The result:

+------+----------------------------------+
| pid  | JSON_ARRAYAGG(c.name)            |
+------+----------------------------------+
|    1 | ["Food", "Fruit", "Dried Fruit"] |
+------+----------------------------------+


来源:https://stackoverflow.com/questions/65669023/mysql-join-in-a-json-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!