search

Home  >  Q&A  >  body text

MySQL: Guide to Opening and Transposing Lists

I have a given data frame:

id Number list
2 [1,2,5,6,7]
5 [1,2,13,51,12]

One of the columns is just the id and the other is a list of numbers like I got from the JSON file before, is there a way to convert it to this format using just MySQL?

id Number list
2 1
2 2
2 5
2 6
2 7
5 1
5 2
5 13
5 51
5 12

I know it can be done easily using Python and pandas, but in this case I just need to use MySQL, and I don't really know how to transpose a list in MySQL

P粉103739566P粉103739566533 days ago562

reply all(2)I'll reply

  • P粉786432579

    P粉7864325792023-09-08 12:08:28

    @Ruslan Pylypiuk

    Postgresql Soul:

    select 
    id,regexp_split_to_table(listofnumbers,',')
    from test

    Mysql Soul: ReferenceSQL split value into multiple rows

    reply
    0
  • P粉883223328

    P粉8832233282023-09-08 10:10:00

    You can use json_table()

    create table myTable(id int, listofnumbers varchar(200));
    insert into myTable values(2,   '[1, 2, 5, 6, 7]');
    insert into myTable values(5,   '[1, 2, 13, 51, 12]');
    select t.id, j.listofnumbers
    from myTable t
    join json_table(
      t.listofnumbers,
      '$[*]' columns (listofnumbers varchar(50) path '$')
    ) j;
    id Number list
    2 1
    2 2
    2 5
    2 6
    2 7
    5 1
    5 2
    5 13
    5 51
    5 12

    reply
    0
  • Cancelreply