将字符串/ varchar转换为MySQL表之间的日期 [英] Convert string/varchar to date between MySQL tables

查看:487
本文介绍了将字符串/ varchar转换为MySQL表之间的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大型的PHP项目,我一直在为自己的业务工作。



我有一个MySQL表,大约2600个条目, d喜欢修复日期。我当前的表有3个包含字符串日期的VARCHAR列。我想把这些转换成一个重复的表,但是改变它们在路上键入DATE。



一旦我进行转换,一切都看起来不错,我将把新表复制到旧数据库中,只允许日期选择器在进行转换时输入这些日期,



大多数现有字符串日期格式为 mm-dd-yyyy ,示例: code> 05-03-2013 。有些是 mm / dd / yyyy ,例如: 05/03/2013 ,还有一些是MONTH DAY ,YEAR格式,例如: 2013年3月26日



我最终想要的是他们是code> yyyy-mm-dd 格式,示例: 2013-05-02



我认为我可以使用PHP,通过strtotime()和date()传递每个字符串日期,但是想知道MySQL是否可以直接执行。

解决方案

看看 STR_TO_DATE 功能:

 更新yourtable 
SET
new_column = STR_TO_DATE(varchar_date,'%m-%d-%Y')
WHERE
STR_TO_DATE(varchar_date,'%m-%d-%Y' )IS NOT NULL

然后同样的查询,日期格式为' %m /%d /%Y',然后再次使用'%M%D,%Y'
如果格式不匹配,STR_TO_DATE将返回NULL,而不会更新行。



如果您希望将现有数据插入到新的表,你可以使用这样的东西:

  INSERT INTO new_table(ID,col1,col2,new_column)
SELECT
ID,col1,col2,
COALESCE(STR_TO_DATE(varchar_date,'%m-%d-%Y'),
STR_TO_DATE(varchar_date,'%m /%d /%Y' )
STR_TO_DATE(varchar_date,'%M%D,%Y'))
FROM oldtable

(new_column是一个日期列,然后您可以格式化您想要使用PHP或使用DATE_FORMAT)


I have a large PHP project that I've been working on for my own business.

I have a MySQL table, with about 2600 entries, that I'd like to "fix" the dates in. My current table has 3 VARCHAR columns that contain string dates. I'd like to convert these, into a duplicate table, but change them to type DATE on the way.

Once I make the conversion and everything looks good, I will copy the new table to the old database, and only allow a date picker to enter those dates on a going-forward basis.

Most of the existing string dates are on the format mm-dd-yyyy, example: 05-03-2013. Some are mm/dd/yyyy, example: 05/03/2013, and a few are of the MONTH DAY, YEAR format, example: March 26th, 2013.

What I ultimately want is them to be of the yyyy-mm-dd format, example: 2013-05-02.

I think I can do this using PHP, passing each string date through strtotime() and then date() but was wondering if MySQL can do this directly.

解决方案

Have a look at STR_TO_DATE function:

UPDATE yourtable
SET
  new_column = STR_TO_DATE(varchar_date, '%m-%d-%Y')
WHERE
  STR_TO_DATE(varchar_date, '%m-%d-%Y') IS NOT NULL

And then the same query, with date format as '%m/%d/%Y', and then again with '%M %D, %Y'. If the format doesn't match, STR_TO_DATE will return NULL and rows won't be updated.

If you wish to insert your existing data to a new table, you could use something like this:

INSERT INTO new_table (ID, col1, col2, new_column)
SELECT
  ID, col1, col2,
  COALESCE(STR_TO_DATE(varchar_date, '%m-%d-%Y'),
           STR_TO_DATE(varchar_date, '%m/%d/%Y'),
           STR_TO_DATE(varchar_date, '%M %D, %Y'))
FROM oldtable

(new_column is a date column, and you can then format how you want using PHP or using DATE_FORMAT)

这篇关于将字符串/ varchar转换为MySQL表之间的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆