简体   繁体   中英

Using JSON_TABLE to convert List into Rows

I have a database column (named "product_parents") formatted as a JSON object that contains the following data:

'["A", "B", "G", "H", "C", "E", "P", "R"]'

I want to use JSON_Table to create separate rows for each item.

Ideally I would get something like:

|product_parent|

|A| |B| |C| |...| |P| |R|

I've tried

SELECT *
    FROM pmctb.products AS p,
    JSON_TABLE (p.product_parents, '$[*]'
        COLUMNS (
                pp_id FOR ORDINALITY,
                pp_pn VARCHAR(255) PATH '$.header')
                ) AS pp
    WHERE product_uid = "310-000574"

($.header was just an attempt since there is no column header) but that just returns the table and the ordinality and gives me nulls for pp_pn.

Any help would be appreciated. Thx

It looks like this does the trick with MySQL 8+:

create table products (product_parents json);

insert into products values ('["A", "B", "G", "H", "C", "E", "P", "R"]');

select pp
from products,
JSON_TABLE(
  products.product_parents,
  '$[*]' columns (pp varchar(255) path '$')
) t;

and the result is:

pp
A
B
G
H
C
E
P
R

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