首頁  >  問答  >  主體

MySQL:開啟和轉置清單指南

我有一個給定的資料框:

id 數字列表
2 [1,2,5,6,7]
5 [1,2,13,51,12]

其中一列只是 id,另一列是數字列表,就像我之前從 JSON 檔案中獲得的那樣,有沒有辦法僅使用 MySQL 將其轉換為這種格式?

id 數字列表
2 1
2 2
2 5
2 6
2 7
5 1
5 2
5 13
5 51
5 12

我知道使用Python和pandas可以輕鬆完成,但在這種情況下我只需要使用MySQL,而且我真的不知道如何在MySQL中轉置清單

P粉103739566P粉103739566409 天前460

全部回覆(2)我來回復

  • P粉786432579

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

    @Ruslan Pylypiuk

    ##Postgresql 靈魂:

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

    Mysql靈魂:參考SQL將值拆分為多行

    #

    回覆
    0
  • P粉883223328

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

    您可以使用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 數字列表
    2 1
    2 2
    2 5
    2 6
    2 7
    5 1
    5 2
    5 13
    5 51
    5 12

    回覆
    0
  • 取消回覆