Search code examples
mysqlsqlcsvphpmyadminload-data-infile

Import csv file with less columns than the table to which I'm importing?


I have exported a csv file with four columns in phpMyAdmin whith these options:

Columns separated with:  ,
Columns enclosed with:   "
Columns escaped with:    "
Lines terminated with:   AUTO

Now I want to import this file into a table with 17 columns!? So only four columns will be populated and the others will stay empty.


Solution

  • You can spcify the column name while import data from file, and use user variable to discard an input value by assigning it to a user variable while import data in table .

    AS PER MYSQL DOCUMENTATION

    You can also discard an input value by assigning it to a user variable and not assigning the variable to a table column:

    LOAD DATA INFILE 'file.txt' INTO TABLE t1 (column1, @dummy, column2, @dummy, column3);

    LOAD DATA INFILE 'filename.csv'  
    INTO TABLE sqlTable(column1, column2, column3, column4, @NotInsert2, @NotInsert2... till @NotInsert13);
    FIELDS TERMINATED BY ','
    LINES TERMINATED BY '\n'
    

    So in Your case, Just specify four column name, and use any user variable instead of others column name so that total number of column in list will be equal to 17.

    EDIT - Lets understand with Example:-

    Consider we have to load file with following contents: File-name: example.csv

    col-2,col-3,col-4
    a,2,3
    b,4,5
    c,6,7
    

    Case :- When csv file have lesser number of columns than targeted table

    table structure: tablename col-1 col-2 col-3 col-4

    Consider, col-1 is auto-increment and not provided in csv.

    LOAD DATA INFILE ‘path/to/example.csv’ 
    INTO TABLE tablename 
    FIELDS TERMINATED BY ‘,’ 
    LINES
    TERMINATED BY ‘\n’ 
    IGNORE 1 LINES (col-2,col-3,col-4) set col-1=null;
    

    Passing null value will make col-1 to take an auto-increment value. Using SET you can assign values to those columns which were not available in csv and are not null.

    For more information refer here