问题
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