Search code examples
mysqlsqlarraysmysql-json

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


Solution

  • 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