PostgreSQL导入CSV报extra data错误(列数匹配仍异常)
PostgreSQL导入CSV报错"extra data after last expected column"的排查与解决
问题根源
核心原因是CSV字段数与表列数不匹配:
- 你提供的CSV第二行包含18个字段(从
0到最后的/cfb/boxscores/2022-12-23-houston.html) data.college_stats表仅定义了17列(从junk到game_id)
PostgreSQL读取到第18个字段时,找不到对应的表列,因此触发"extra data after last expected column"错误。
解决办法
1. 补全表列,匹配CSV字段数
在表中新增一列来容纳CSV中多余的字段,示例SQL:
ALTER TABLE data.college_stats ADD COLUMN extra_field VARCHAR;
如果知道该字段的实际含义,可以给它起更合适的名称(比如game_detail_url)。
2. 确保COPY语句列名与CSV顺序完全对应
指定列名执行COPY时,必须保证列的数量和顺序与CSV字段完全匹配,示例:
COPY data.college_stats (junk, player, school, rush_att, rush_yds, rush_avg, rush_td, rec_yds, rec_avg, rec_td, total_plays, total_yds, total_avg, total_td, player_id, school_id, game_id, extra_field) FROM '/Users/path/All Items/Football Data/2022CFBrushingandreceiving.csv' DELIMITER ',' CSV HEADER;
3. 清理CSV字段的多余空格
注意到CSV中部分字段前后带有空格(比如, Ta'Zhawn Henry, Houston,),这些空格会被当作字段内容的一部分。如果不需要这些空格,可以:
- 手动编辑CSV,批量去除字段前后的空格
- 或者使用
TRIM()函数在导入时处理,示例:
COPY data.college_stats (junk, player, school, rush_att, rush_yds, rush_avg, rush_td, rec_yds, rec_avg, rec_td, total_plays, total_yds, total_avg, total_td, player_id, school_id, game_id, extra_field) FROM '/Users/path/All Items/Football Data/2022CFBrushingandreceiving.csv' DELIMITER ',' CSV HEADER (junk = TRIM(junk), player = TRIM(player), school = TRIM(school));
内容的提问来源于stack exchange,提问作者Edward Gorelik
相关产品推荐
相关产品推荐

