mysql的str to date_MySQL的STR_TO_DATE不工作

bd96500e110b49cbb3cd949968f18be7.png

I have a table with a varchar column called birthday

CREATE TABLE IF NOT EXISTS `test` (

`id` int(11) NOT NULL AUTO_INCREMENT,

`birthday` varchar(30) COLLATE utf16_unicode_ci NOT NULL,

PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf16 COLLATE=utf16_unicode_ci AUTO_INCREMENT=5 ;

INSERT INTO `test` (`id`, `birthday`)

VALUES (1, '20041225'),

(2, '2004-12-25'),

(3, '19941225'),

(4, '19941201');

I try to run this query:

SELECT str_to_date(birthday,"%Y%m%d")

FROM `test`

WHERE 1

But it always return rows with null values.

If I run the query:

SELECT str_to_date('20141225',"%Y%m%d")

FROM `test`

WHERE 1

It will return 2014-12-25

So what wrong with my query?

解决方案

Leave it to simpler functions. DATE() returns the date part of a string in YYYY-MM-DD format:

SELECT DATE(birthday) FROM `test`

Result:

2004-12-25

2004-12-25

1994-12-25

1994-12-01

The reason your code isn't working is that STR_TO_DATE() expects the same input and output formats, e.g. STR_TO_DATE('2014-08-29', '%Y-%m-%d'). Take a look at the examples in the documentation. This function is used mostly to convert dates or times from one format to another, where the original format is something from outside MySQL and you want to import the data into MySQL's date format for example - in this case, you'll know what the original date format is.

Example:

SELECT STR_TO_DATE('20041225', '%Y-%m-$d'); -- null - formats don't match

SELECT STR_TO_DATE('2004-12-25', '%Y-%m-%d'); -- 2004-12-25 - formats match

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值