简体   繁体   中英

import tab separated csv file with partial data into mysql table with phpMyAdmin

I have a MySQL table which has about 30 columns. I have a CSV file which has about 10 columns.

I want to use phpMyAdmin to update the data from the CSV file in the database without changing the rest of the data.

For example, the MySQL would be:

id, code,  name,     description, a,   b,   c,   x,  y,   z
10, rbmls, Joe Blow, Neighbor,    100, 200, 500, 80, 800, 10

The CSV could contain:

id[TAB]code [TAB]a [TAB]b  [TAB]c
10[TAB]rbmls[TAB]10[TAB]300[TAB]0

I want to match the data in the CSV and the MySQL table by ID and then overwrite the data from the CSV in the MySQL table without deleting anything else.

The desired result of the above example would be:

id, code, name, description, a, b, c, x, y, z
10, rbmls, Joe Blow, Neighbor, 10, 300, 0, 80, 800, 10

How do I do that in phpMyAdmin?

LOAD DATA INFILE has a column-specification at the end. see here

LOAD DATA INFILE ... 
INTO TABLE ... 
FIELDS TERMINATED BY '\t'
IGNORE 1 LINES
(id, code, a, b, c)

From MySQL-Doc:

By default, when no column list is provided at the end of the LOAD DATA INFILE statement, input lines are expected to contain a field for each table column. If you want to load only some of a table's columns, specify a column list: LOAD DATA INFILE 'persondata.txt' INTO TABLE persondata (col1,col2,...);

Alternative

Load the data in a temporary table and do an INSERT ... UPDATE from there to the main-table. Something like that:

LOAD DATA INFILE ... INTO TABLE `temp` ...

INSERT INTO mainTable (id, code, a, b, c)
SELECT * FROM `temp`
  ON DUPLICATE KEY UPDATE code=VALUES(code), a=VALUES(a), b=VALUES(b), c=VALUES(c);

See here

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