首页 > 解决方案 > 从 mysql 中的 csv 文件加载数据时无法转换日期格式

问题描述

我正在尝试将 CSV 文件中的数据加载到表中。CSV 文件中的数据有两个日期列,其日期格式为 MM/DD/YYYY,但我希望在加载数据时使用 YYYY-MM-DD 格式的日期。

这是我的表结构

create table Sales
(
  region varchar(100) not null,
  country varchar(100) not null,
  item_type varchar(50) not null,
  sales_channel varchar(50) not null,
  order_priority varchar(10) not null,
  order_date date null,
  order_id bigint not null,
  ship_date date null,
  units_sold decimal(10,5) null,
  unit_price decimal(10,5) null,
  unit_cost decimal(10,5),
  total_revenue decimal(15,5) null,
  total_cost decimal(15,5) null,
  total_profit decimal(15,5) null,
  primary key(order_id)
);

This is the command I'm using to load the data from CSV file
LOAD DATA INFILE '/var/lib/mysql-files/Sales_Record.csv'
INTO TABLE Sales
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS
(region,
  country,
  item_type,
  sales_channel,
  order_priority,
  order_date,
  order_id,
  ship_date,
  units_sold,
  unit_price,
  unit_cost,
  total_revenue,
  total_cost,
  total_profit 
)
set order_date = STR_TO_DATE(order_date,'%mm/%dd/%yyyy')
set ship_date = STR_TO_DATE(ship_date,'%mm/%dd/%yyyy');

运行命令时出现以下错误

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 'set ship_date = STR_TO_DATE(ship_date,'%mm/%dd/%yyyy')'

标签: mysqldate

解决方案


推荐阅读