加载数据infile错误:MySQL在指定列时抛出语法错误

时间:2014-05-26 17:43:07

标签: mysql load-data-infile

StackOverflowers!

尝试将.csv文件导入表格时出现问题。

据我所知(正如我在reference manual中所读到的),语法是这样的:

load data infile '/path/to/my/file.csv'
    into table myTable(field1, field2, field3,..., fieldk)
    fields terminated by ',' optionally enclosed by '"'
    lines terminated by '\n'
    ignore 1 lines;

但是,MySQL客户端会抛出此错误:

  

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'fields terminated by ',' optionally enclosed by '"' lines terminated by '\n'

我需要指定列列表,因为我的表中有一个列不存在于文件中(id列)。

我已经检查(并重新检查)了语法,一切似乎都没问题......所以我不知道哪些是错的。我试过在反引号(`)中包含字段名称,但它也不起作用......字段列表是错误的吗?我是否需要指定我缺少的东西?

背景信息:

  • OS:Debian 7.5(wheezy),64位
  • MySQL版本:5.5.37-0 + wheezy1
  • 所有表格均为MyISAM

尝试解决方案:

当然,我可以创建一个临时表并删除“有问题”列。我已经测试了这个解决方案,它可以工作:

drop table if exists temp_myTable;
create temporary table temp_myTable like myTable;
alter table temp_myTable drop column id;
load data infile '/path/to/my/file.csv'
    into table temp_myTable
    fields terminated by ',' optionally enclosed by '"'
    lines terminated by '\n'
    ignore 1 lines;
insert into myTable (field1, field2, ... fieldk)
    select field1, field2, ... fieldk
    from temp_myTable;
drop table if exists temp_myTable;

但是,我认为这非常麻烦......为什么我应该用一个指令解决它时应该编写6条指令?

你能帮帮我吗?

1 个答案:

答案 0 :(得分:3)

在仔细阅读参考手册之后,我发现编写列列表的正确方法是在句子的末尾

load data infile '/path/to/my/file.csv'
    into table myTable
    fields terminated by ',' optionally enclosed by '"'
    lines terminated by '\n'
    ignore 1 lines
    (field1, field2, field3,..., fieldk); -- The field list goes here

现在,我感到非常愚蠢......但我把这些知识放在这里,以防万一有人面临同样的问题。

相关问题