有时候,在使用LOAD DATA LOCAL INFILE时,文件中列顺序或者数量与数据库表并不相同,这时候需要指定列名。网上很多帖子的写法是错误的,将列名跟在表名之后,会报语法错误。
根据语法规则:
load data [low_priority] [local] infile 'file_name txt' [replace | ignore]
into table tbl_name
[fields
[terminated by't']
[OPTIONALLY] enclosed by '']
[escaped by'\' ]]
[lines terminated by'n']
[ignore number lines]
[(col_name, )]
因此正确做法是列名需要放在Fields的后面,例如:
test.txt内容:
a1|a2
b1|b2
c1|c2
d1|d2
e1|e2
mysql中表结构为:col1 col2 col3
则加载命令为:
LOAD DATA LOCAL INFILE 'test.txt' INTO TABLE tblTest FIELDS TERMINATED BY '|' (col1, col2);
还可以指定col3:
LOAD DATA LOCAL INFILE 'test.txt' INTO TABLE tblTest FIELDS TERMINATED BY '|' (t1, t2, t3) SET t3='3';