MYSQL -- Split a row into multiple rows based on JSON columns

Use JSON_TABLE

For example, if there is a json field json_filed in the table,
insert image description here
we want to achieve the following effects
insert image description here
. You can use json_table to achieve it. json_table can convert the json field into a table for use.

SELECT json_field,j.json_single_value FROM `user`
left join 
json_table(json_field, '$[*]' columns (json_single_value int path '$')) as j on true

The query results are as follows, divided by one line into multiple lines
insert image description here

Incorrect arguments to JSON_TABLE

Sometimes we use subqueries, as follows

SELECT a.json_field,j.json_single_value FROM 
( select * from `user` where 1=1) as a
left join json_table(a.json_field, '$[*]' columns (json_single_value int path '$')) as j on true

We need to filter the target table first to save memory and improve query efficiency, and then convert its json field to table,
but when we run the above SQL, an error of Incorrect arguments to JSON_TABLE will pop up.
The reason is that there is a problem with the format of the json_field field in our subquery, and we need to force conversion

SELECT a.json_field,j.json_single_value FROM 
( select * from `user` where 1=1) as a
left join json_table(CAST(a.json_field AS JSON), '$[*]' columns (json_single_value int path '$')) as j on true

Guess you like

Origin blog.csdn.net/qq_40096897/article/details/130288773