How I can Import data from CSV to MySQL?

2019-01-09 16:35发布

问题:

I have csv file with following structure:

    A   BA0011  U206    NAME    0000000000000149.00     000000.00  0000000000000118.93  S   N   N
    A   BB0011  U206    NAME    0000000000000150.00     000000.00  0000000000000118.93  S   N   N
    A   BC0011  U206    NAME    0000000000000151.00     000000.00  0000000000000118.93  S   N   N
    A   BD0011  U206    NAME    0000000000000152.00     000000.00  0000000000000118.93  S   N   N
    A   BE0011  U206    NAME    0000000000000153.00     000000.00  0000000000000118.93  S   N   N

Using following MySQL Function How I can import first and third column in MySQL table:

LOAD DATA INFILE 'data.csv' INTO TABLE tbl_name
  FIELDS TERMINATED BY \t' ENCLOSED BY '"'
  LINES TERMINATED BY '\r\n'
  IGNORE 1 LINES;

I apologize for my English!

Thanks in advance !

回答1:

You can specify the columns and mark the unnecessary columns as '@dummy'.

LOAD DATA INFILE 'data.csv'
INTO TABLE t1
(column1, @dummy, column2, @dummy, @dummy, @dummy, @dummy, @dummy, @dummy, @dummy)
FIELDS TERMINATED BY '\t' ENCLOSED BY 
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES;

Replace t1, column1 and column2 as you like. To set other columns which are not in the data file, you can do it like this:

LOAD DATA INFILE 'data.csv'
INTO TABLE t1
(column1, @dummy, column2, @dummy, @val, @dummy, @dummy, @dummy, @dummy, @dummy)
FIELDS TERMINATED BY '\t' ENCLOSED BY 
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES
SET column3 = "test", column4 = CURRENT_TIMESTAMP, column5 = @val/10;

For further reference, I recommend you to take a look at the MySQL reference.



回答2:

Perhaps you could import it into a table that has all the columns (to match the CSV), then select-insert it into your target table?



标签: mysql csv import