简体   繁体   中英

Mysql explode json array to rows

From a table with a column with json array of dictionaries i need to extract all values of key "user_id" one per row. If null or empty array return NULL. Similar to python pandas explode method.

Length of array is unknown.

Original table:

| id | users                                                           |
|----|-----------------------------------------------------------------|
|  1 |[{"id": 2, "mail": "u1@ab.com"}, {"id": 3, "mail": "u2@ab.com"}] |
|  2 |[{"id": 5, "email": "user3@hi.com"}]"                            |
|  3 | []
                                                           |

Processed table:

| id | users    |
|----|----------|
|  1 | 2        |
|  1 | 3        |
|  2 | 5        |
|  3 | NULL     |
select id, j.user_id from mytable left outer join 
json_table(users, '$[*]' columns (user_id int path '$.user_id')) as j on true;

+------+---------+
| id   | user_id |
+------+---------+
|    1 |       2 |
|    1 |       3 |
|    2 |       5 |
|    3 |    NULL |
+------+---------+

Read https://dev.mysql.com/doc/refman/8.0/en/json-table-functions.html for more information on the JSON_TABLE() function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM