我正在尝试将CSV文件导入MySQL数据库表。 CSV行如下所示:
"00602"," ","42042","15590","0","0","0","35","9","67","1978","20608","21434","3.1","54700","11384","31.3","30.4","32","18.382809","-67.186759","0","PR","Puerto Rico","U","","787","AGUADA","URB SAN CRISTOBAL","AGUADA","003","72","4","N","0060","","","10380","","Metro","Aguadilla-Isabela-San Sebastián PR","Aguadilla PR MSA","","","","N","0","0","0","0","","0","0","0","0","0","322569","0","","","5456","415","9577","V17136"," "," ","",""
"00602"," ","42042","15590","0","0","0","35","9","67","1978","20608","21434","3.1","54700","11384","31.3","30.4","32","18.382809","-67.186759","0","PR","Puerto Rico","U","","787","AGUADA","COMUNIDAD LAS FLORES","AGUADA","003","72","4","N","0060","","","10380","","Metro","Aguadilla-Isabela-San Sebastián PR","Aguadilla PR MSA","","","","N","0","0","0","0","","0","0","0","0","0","322569","0","","","5456","415","9577","V17136"," "," ","",""
etc...
如您所见,字段用双引号括起来,并以逗号分隔。但是有些行在值内部有逗号(注意最后一个值):
"00501"," ","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","40.81518","-73.0455","25","NY","New York","N","","631","HOLTSVILLE","I R S SERVICE CENTER","SUFFOLK","103","36","5","Y","5602","5380","408","35620","35004","Metro","New York-Northern New Jersey-Long Island NY-NJ-PA","New York-Northern New Jersey-Long Island","Nassau-Suffolk, NY PMSA","Northeast","Middle Atlantic","N","7","0","0","0","B","0","0","0","0","0","18640775","2807500","","","0","1","1","V13916","U"," ","New York-Newark-Bridgeport, NY-NJ-CT-PA","Nassau-Suffolk, NY"
这是我的import语句的样子:
LOAD DATA INFILE '/file.csv'
REPLACE INTO TABLE zipcodes
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n';
但它没有按预期工作。例如,第一个插入的行具有一个具有以下值的列:
Nassau-Suffolk, NY""00501
相反应该是:
Nassau-Suffolk, NY
和00501
应该作为第一列值插入到下一行。
如何调整我的SQL工作正常?
答案 0 :(得分:18)
从MySQL Reference Manual,请改用以下选项:
LOAD DATA INFILE 'data.txt' INTO TABLE tbl_name
FIELDS TERMINATED BY ',' ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
更新以符合您的使用情况,但重要的是从OPTIONALLY
中删除OPTIONALLY ENCLOSED BY
。