mysql STR_TO_DATE not working

夙愿已清 提交于 2019-12-22 09:19:51

问题


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?


回答1:


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



回答2:


You have COLLATE problem with your creation of table. If you use utf8_unicode_ci then there is no any problem. See this example on sqlfiddle. More about collation you can read this Post.



来源:https://stackoverflow.com/questions/25561169/mysql-str-to-date-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!