How to Map CSV Column Names Differently When Importing Data into MySQL?

Linda Hamilton
Release: 2024-10-24 03:10:29
Original
677 people have browsed it

How to Map CSV Column Names Differently When Importing Data into MySQL?

How to Import a CSV File into MySQL with Different Column Names

In this article, we'll guide you through importing a CSV file into a MySQL table, even when the column names differ.

To facilitate this process, you can use a query that includes the LOAD DATA INFILE syntax. This approach allows you to specify which CSV column will be imported into which database column, even if the names are different.

Syntax

LOAD DATA INFILE 'csv_file_path' INTO TABLE table_name (column_name1, column_name2, ...);
Copy after login

Example

Assuming you have a CSV file named data.csv with the following data:

<code class="csv">uniq_name,uniq_city,uniq_comment
John Doe,New York,This is John's comment
Jane Smith,Los Angeles,This is Jane's comment</code>
Copy after login

And a MySQL table named my_table with the following columns:

id,name,city,comments
Copy after login

You can use the following query to import the CSV data into the my_table table, mapping the columns accordingly:

<code class="sql">LOAD DATA INFILE 'data.csv' INTO TABLE my_table (id, name, city, comments);</code>
Copy after login

Additional Notes

  • Make sure that the CSV file path is correct and accessible.
  • Ensure that the data types in the CSV file match the corresponding columns in the database table.
  • You can use the INTO IGNORE clause to ignore duplicate records.
  • If you encounter any issues during the import process, review the MySQL documentation for additional troubleshooting tips.

The above is the detailed content of How to Map CSV Column Names Differently When Importing Data into MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template