Home > Database > Mysql Tutorial > How to Import CSV Data into MySQL, Skipping the First Row and Auto-Incrementing the Primary Key?

How to Import CSV Data into MySQL, Skipping the First Row and Auto-Incrementing the Primary Key?

Mary-Kate Olsen
Release: 2024-11-11 03:35:02
Original
1098 people have browsed it

How to Import CSV Data into MySQL, Skipping the First Row and Auto-Incrementing the Primary Key?

Import CSV to MySQL: Skipping the First Row and Auto-Incrementing Primary Key

When importing data from a CSV file to a MySQL table, it may be necessary to skip the first row of the CSV file, which typically contains column headers, and also to have MySQL automatically generate values for a primary key column.

Skipping the First Row

To skip the first row of the CSV file during import, use the IGNORE keyword in the LOAD DATA statement:

LOAD DATA INFILE 'path/to/file.csv'
INTO TABLE your_table
IGNORE 1 LINES
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n';
Copy after login

Auto-Incrementing Primary Key

If your table's primary key column is set to auto-increment, you can leave it out of the CSV file, and MySQL will automatically generate values for it during import. To do this, specify NULL for the primary key column in the SET clause:

LOAD DATA INFILE 'path/to/file.csv'
INTO TABLE your_table
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
SET>
Copy after login

Example

Consider the CSV file provided in the question, which is missing the first row (column headers) and the id column. To import this data into a MySQL table named advertisement with an auto-incrementing primary key column named id, use the following SQL statement:

LOAD DATA INFILE 'path/to/file.csv'
INTO TABLE advertisement
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
IGNORE 1 LINES
SET>
Copy after login

The above is the detailed content of How to Import CSV Data into MySQL, Skipping the First Row and Auto-Incrementing the Primary Key?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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