当尝试使用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上添加数据时,即使在范围内,数据检索也非常快,例如:
DATE
INDEX
SELECT * FROM Estimates WHERE CreatedDate BETWEEN '2016-01-01' AND '2016-06-30'