Default value for empty integer fields when importing CSV data in MySQL

后端 未结 3 1169
渐次进展
渐次进展 2021-02-09 09:35

I\'m importing a CSV into a MySQL table with LOAD DATA INFILE. One of the table\'s fields stores zip code data, which I\'ve defined in the table structure con

相关标签:
3条回答
  • 2021-02-09 10:07

    In Csv I replaced all the "" with "\N" before I run the script, this creates a null field in db

    0 讨论(0)
  • 2021-02-09 10:09

    The empty values are being interpreted as the empty string (''), not NULL, so the default value is not being used.

    If you want to explicitly control the handling of these empty strings, the best thing to do is to load them into a user variable, and then set the column conditionally using the user variable.

    You could use this to set the value to whatever you want (NULL, 0, etc.).

    Here's an example, assuming you want to set it to 0:

    LOAD DATA INFILE '...'
    INTO TABLE your_table
    FIELDS TERMINATED BY ','
    (column_one,..., @contributor_zipcode,..., column_n)
    SET contributor_zipcode = IF(@contributor_zipcode='',0,@contributor_zipcode);
    
    0 讨论(0)
  • 2021-02-09 10:23

    For some elements (e.g. zip codes), may be better for default value to be null, not 0.

    Assume you have a table of people called (what else) People.

    create table People (
        id int,
        first_name varchar(30),
        last_name varchar(50),
        city varchar(50),
        state varchar(50),
        zip int
    );
    

    Next, load your file.csv into the People table. Note the last line (starting with set) where zip is assigned null if the value in the file is "" (aka an empty string)

    load data local infile '/path/to/file.csv'
    into table People
    fields 
        terminated by ','
        enclosed by '"'
    lines terminated by '\n'
    (id, first_name, last_name, city, state, @zip)
    set zip = if(@zip='', null, @zip);
    
    0 讨论(0)
提交回复
热议问题