简体   繁体   English

如何将MySQL列从VARCHAR更改为日期时间并同时转换数据?

[英]How can I change a MySQL column from VARCHAR to date time and convert the data at the same time?

I have a large set of data with a varchar column which contains an unusual date time format. 我有一个带有varchar列的大量数据,其中包含不寻常的日期时间格式。

How can I both convert the data in the 6000+ rows, and then convert the column's type? 如何同时转换6000多个行中的数据,然后转换列的类型?

I can see that it's possible to convert the type with this: 我可以看到可以使用以下方式转换类型:

ALTER TABLE <tblName> MODIFY <columnName> date time;

But I don't see how I can keep the data and do this for all rows at the same time. 但是我看不到如何保留数据并同时对所有行执行此操作。

An example date that I currently have is: 我当前的日期示例是:

Mon, 23 Sep 2013 07:01:00 GMT

Answer as per @Mihai 根据@Mihai回答

UPDATE rns
SET rns.`rns_pub_date` = STR_TO_DATE(rns_pub_date,"%a, %d %b %Y")

You don't do it all at once. 您不会一次完成所有操作。 You take these steps, one by one. 您一步一步地执行这些步骤。

  1. Add the new column. 添加新列。
  2. Update the new column from the old column. 从旧列更新新列。 This may take more than one query depending on how many formats you have in your varchar column. 这可能需要多个查询,具体取决于varchar列中有多少种格式。
  3. Drop your old column. 删除旧列。
  4. Rename your new column. 重命名新列。
UPDATE `table`
SET `column` = STR_TO_DATE(`column`,'%Y-%m-%d')

Adapt the format to your needs. 根据您的需求调整格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM