当尝试使用str_to_date()将我的Estimates表中的字符串日期值的列CreatedDate转换为mySQL日期格式时,我一直收到错误消息。我的数据列包含m / d / yy格式的日期(例如:1/26/16或3/3/16)。

我跑了这个查询:

UPDATE Estimates
SET CreatedDate = str_to_date( CreatedDate, '%c/%e/%y' )

mySQL返回此错误消息:
Error
SQL query:
UPDATE Estimates
SET CreatedDate = str_to_date( CreatedDate, '%c/%e/%y' )
MySQL said: #1411 - Incorrect datetime value: '' for function str_to_date

我的查询出了什么问题?

最佳答案

清理数据的通常策略如下:

ALTER TABLE Estimates CHANGE COLUMN CreatedDate CreatedDateString VARCHAR(255);
ALTER TABLE Estimates ADD COLUMN CreatedDate DATE

UPDATE Estimates SET CreatedDate=STR_TO_DATE(CreatedDateString, '%c/%e/%y'))
  WHERE CreatedDateString IS NOT NULL AND CreatedDateString != ''

然后,当您确信一切都正确转换后:
ALTER TABLE Estimates DROP COLUMN CreatedDateString

正确的DATE字段的优点是它们的格式一致,并且当您在它们上添加INDEX时,数据检索非常快,即使在范围内,例如:
SELECT * FROM Estimates WHERE CreatedDate BETWEEN '2016-01-01' AND '2016-06-30'

10-06 05:22