在数据库级别将 mysql 中的 varchar 列转换为日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14378003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert varchar column to date in mysql at database level
提问by Pratik Prajapati
I have one column date1
which is varchartype
I want this column to date
type.
I tried changing field but all date is converted to 0000-00-00
.
format is dd-mm-yyyy
but in varchar.
我有一个varchar类型的列date1
,我希望此列输入。我尝试更改字段,但所有日期都转换为. 格式只是varchar。date
0000-00-00
dd-mm-yyyy
How can I convert the same date format but with date format using sql queries or similar but at database level ?
如何使用 sql 查询或类似但在数据库级别转换相同的日期格式但使用日期格式?
回答by hjpotter92
UPDATE `table`
SET `column` = str_to_date( `column`, '%d-%m-%Y' );
More about STR_TO_DATEfunction.
有关STR_TO_DATE函数的更多信息。
Since your column name is date1
, you can replace column
with date1
in the above syntax, and the code shall be:
由于你的列名是date1
,你可以用上面的语法替换column
,date1
代码应该是:
UPDATE `table`
SET `date1` = str_to_date( `date1`, '%d-%m-%Y' );
回答by PeteW
The other answers here are risky, because if they go wrong you'll lose your data. A safer way to do this is to create a new field on your database with a DATE (or DATETIME if you need time as well) format, then to run a query like
这里的其他答案有风险,因为如果出错,您将丢失数据。一种更安全的方法是在您的数据库上创建一个具有 DATE(或 DATETIME,如果您还需要时间)格式的新字段,然后运行如下查询
UPDATE `table` SET `my_new_date_field` = STR_TO_DATE( `my_old_data_field`, '%d/%m/%Y');
In this way, if the %d/%m/%Y
bit is wrong, you won't lose your data.
这样,如果%d/%m/%Y
位错了,您就不会丢失数据。
Once you're happy, you can delete the old data field and rename the new one.
满意后,您可以删除旧数据字段并重命名新数据字段。
回答by Dhruv Patel
use STR_TO_DATEFunction of MySQL
使用MySQL 的STR_TO_DATE函数
FIRST you will need to update the value in date format.
首先,您需要更新日期格式的值。
UPDATE `tbl` SET `date1` = STR_TO_DATE(`date1`, '%d-%m-%Y') WHERE 1=1
THEN Convert the field to date.
然后将字段转换为日期。
Most importantly remember to insert date as Y-m-d format, after then.
最重要的是记住在此之后将日期插入为 Ymd 格式。