mysqlload-data-infile

MySQL load data insert, split values to multiple rows


Using the LOAD DATA LOCAL INFILE

num column Store every 6 digits

How can I parameterize the load command to iterate through the array?

Mysql version 8.0.23

In File text

id length 1,
cnt length 2,
num length 500
--------------------
1 3AB1001AB1002AB1003

table A

id cnt num
1 3 AB1001AB1002AB1003

i want output like this table

table B

id cnt num
1 3 AB1001
1 3 AB1002
1 3 AB1003

Solution

  • I was able to test this table:

    create table mytable (
      id int,
      cnt int,
      num varchar(500)
    );
    

    I put the line of text you show into a file p.csv:

    1 3AB1001AB1002AB1003
    

    I ran the mysql client with the option to enable local data loading:

    $ mysql --local-data
    

    Then I loaded the data file this way:

    mysql> load data local infile 'p.csv' into table mytable (@temp)
    set id = substr(@temp, 1, 1),
        cnt = substr(@temp, 2, 2),
        num = substr(@temp, 3);
    

    It worked!

    mysql> select * from mytable;
    +------+------+---------------------+
    | id   | cnt  | num                 |
    +------+------+---------------------+
    |    1 |    3 | 3AB1001AB1002AB1003 |
    +------+------+---------------------+
    

    Read more about the LOAD DATA INFILE statement here: https://dev.mysql.com/doc/refman/8.0/en/load-data.html

    And read about the SUBSTR() function here: https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_substr