How to insert selected columns from a CSV file to a MySQL database using LOAD DATA INFILE

Ugesh Gali picture Ugesh Gali · Nov 17, 2010 · Viewed 116k times · Source

I have a CSV file which contains 10 columns. I want to select only some columns from that file and load them into a MySQL database using the LOAD DATA INFILE command.

Answer

ArK picture ArK · Nov 17, 2010

Load data into a table in MySQL and specify columns:

LOAD DATA LOCAL INFILE 'file.csv' INTO TABLE t1 
FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n'  
(@col1,@col2,@col3,@col4) set name=@col4,id=@col2 ;

@col1,2,3,4 are variables to hold the csv file columns (assume 4 ) name,id are table columns.