简体   繁体   中英

Using LOAD DATA INFILE statement when csv table headings don't match mySQL table headings?

What I'm looking to do is import some .CSV files into mySQL using php .

I'm going to be using the LOAD DATA INFILE statement but I have an issue:

The headers in the .CSV file don't match up with the columns in the mySQL table, there are way more in the .CSV file. I know I can ignore certain columnhs by using a variable like:

$insert_query = "LOAD DATA LOCAL INFILE $csvfile
            INTO table $tableName
            FIELDS TERMINATED BY ','
            LINES TERMINATED BY ''
            (col1,col2,col3,@ignore,col4)";

What I would like to know is if I can assign the columns of data in the .CSV file to different columns in the mySQL table, EG mapping the first column of data in the .CSV to the fifth column of the mySQL table, kind of like:

$insert_query = "LOAD DATA LOCAL INFILE $csvfile
            INTO table $tableName
            FIELDS TERMINATED BY ','
            LINES TERMINATED BY ''
            (col5,col2,col3,@ignore,col4)";

Is this possible? If so, some examples would be greatly appreciated! :)

Thanks!

You do this using the appropriate syntax for your problem and specify a column list:

LOAD DATA INFILE 'path/to/your/file' INTO TABLE yourTable (col1,col2,...);

The manual states further:

You must also specify a column list if the order of the fields in the input file differs from the order of the columns in the table. Otherwise, MySQL cannot tell how to match input fields with table columns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM