1, in the practical application projects you need to query the last full month of data, because of his previous projects with similar queries. So we use STR_TO_DATE function as a condition. It was found that using the wrong one. WRONG:
SELECT COUNT(1) FROM tf_u_user WHERE CREATE_TIME >= STR_TO_DATE('2019-04','%Y-%m') AND CREATE_TIME < STR_TO_DATE('2019-05', '%Y-%m');
The problem with this method is that STR_TO_DATE () when this function, the date format is not only to format the date, the date will be formatted, such STR_TO_DATE ( '2019-04', '% Y-% m') It is equivalent to '2019-03-31'. Therefore, an error occurred.
select STR_TO_DATE('2019-04','%Y-%m'); --- “2019-03-31”
Use this query to find and expected results are not the same, so using another method.
SELECT * FROM tf_u_user WHERE PERIOD_DIFF(date_format(NOW(),'%Y%m' ) , date_format(CREATE_TIME,'%Y%m')) =1;
Optimization and added:
Use this method resolved STR_TO_DATE () function in the pit, but can only query data last month, and that if the investigation phase last month how to do, and then a little earlier data is what to do?
1 may be modified as = = 2 and the like.
Of course, this is just one way. Not the best. But effective in actual use, at the same time I want to record this pit. To do this as a reminder. Any function of time in the next test. We can not rely on experience.
Also this error is not enough on its own understanding STR_TO_DATE this function, it shall not be treated using the method, if it is written the date is also possible.
SELECT COUNT(1) FROM tf_u_user WHERE CREATE_TIME >= STR_TO_DATE('2019-04-01','%Y-%m-%d') AND CREATE_TIME < STR_TO_DATE('2019-05-01', '%Y-%m-%d');
Such queries can also write data in April. You may be specifically selected depending on the application.