简体   繁体   English

MySQL-将.CSV / Excel文件导入MySQL

[英]MySQL - Import .CSV/Excel file into MySQL

How do I do it when I want to Import a csv/excel file but I want the contents to be in a specific column? 当我要导入csv / excel文件但希望内容在特定列中时,该怎么办?

I have 6 columns in my database. 我的数据库中有6列。 Let's just call it a, b, c, d, e, f. 我们就称它为a,b,c,d,e,f。

I want to insert contents to c, d, e from the excel file. 我想将内容从Excel文件插入到c,d,e。 Contents of the column a, b and f would be automatically generated. a,b和f列的内容将自动生成。

I'm using the LOAD DATA INFILE script. 我正在使用LOAD DATA INFILE脚本。

One option is to specify user-defined variables as a target for a fiel, in the place of a column name in the column list at the end of the LOAD DATA statement. 一种选择是将用户定义的变量指定为该字段的目标,而不是在LOAD DATA语句末尾的列列表中的列名。

For example (omitting most of the syntax): 例如(省略大部分语法):

LOAD DATA ... 
...     
(@dummy1, @dummy2, c, d, e, @dummy3)

The first field from a line will be assigned to user-defined variable @dummy1, the second field to another user-defined variable, the third, fourth and fifth fields will be assigned to columns c, d, and e (respectively), the sixth field will be assigned to another user-defined variable. 行中的第一个字段将分配给用户定义的变量@ dummy1,第二个字段将分配给另一个用户定义的变量,第三,第四和第五个字段将分别分配给c,d和e列,第六字段将分配给另一个用户定义的变量。

If you want to provide a value for a column that's the result of an expression, you can use the SET clause... 如果要为作为表达式结果的列提供值,则可以使用SET子句...

LOAD DATA ... 
...     
(@a, @b, c, d, e, @dummy3) 
SET a = UPPER(@a) 
  , b = STR_TO_DATE(@b,'%m/%d/%Y')
  , f = CONCAT(@a,@b)

UPDATE 更新

If you only have three fields in the csv, and you want to assign the first field to column c , the second field value to column d , and the third field value to column e ... 如果您在csv中只有三个字段,并且想要将第一个字段分配给c列,将第二个字段值分配给d列,并且将第三个字段值分配给e列...

LOAD DATA ...
...
(c, d, e)

It's the position of the column name in the (col_or_user_var,...) list that determines which field value will be assigned to which column. 这是列名的位置 (col_or_user_var,...)列表,确定哪个字段值将被分配给列。 To "skip" a field, assign it to user-defined variable... the field in the file has to be assigned to something, and if you don't want to assign it to a column, the assign it to user-defined variable. 要“跳过”字段,请将其分配给用户定义的变量...文件中的字段必须分配给某些内容,如果您不想将其分配给列,则将其分配给用户定义变量。

It wasn't clear in your question how many fields were in the file, and which field should be assigned to which column. 您的问题尚不清楚,文件中有多少个字段,应该将哪个字段分配给哪个列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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