简体   繁体   English

为什么MySQL选择日期在不同月份不起作用

[英]why is MySQL select date not working for different month

I have a very old database I made when I was still learning PHP and MySQL. 当我仍在学习PHP和MySQL时,我有一个非常老的数据库。 If I populate: 如果我填充:

SELECT * FROM Jobs WHERE (date BETWEEN 'Aug.01 2016' AND 'Aug.31 2016')

I can actually populate rows 我实际上可以填充行

Found rows: 4 Warnings: 0 Duration for 1 query: 0.000 sec.

But once I change my month (moving the range from Aug 1 to July 1): 但是,一旦我更改了月份(将范围从8月1日移至7月1日):

SELECT * FROM Jobs WHERE (date BETWEEN 'Jul.01 2016' AND 'Aug.31 2016')

I got nothing even so the range July 1 ~ Aug 31 includes Aug 1 ~ Aug 31 (from previous example), which should populate at least 4 rows 我什至什么也没有,所以范围7月1日至8月31日包括8月1日至8月31日(来自上一个示例),该范围应至少填充4行

Found rows: 0 Warnings: 0 Duration for 1 query: 0.016 sec.

Is there a way I can populate the rows even they have different month? 有没有一种方法可以填充行,即使它们的月份不同?

You need to first convert your date string to a valid date: 您需要先将日期字符串转换为有效日期:

SET @date := 'Aug.01 2016';

SELECT STR_TO_DATE(@date,'%M.%d %Y');

Output(yyyy-mm-dd): 2016-08-01 产量(yyyy-mm-dd): 2016-08-01

Now use this in your query to search for result having dates between 2016-07-01 & 2016-08-31 . 现在,在查询中使用此命令搜索日期介于2016-07-01 & 2016-08-31之间的结果。

SELECT 
*
FROM Jobs 
WHERE STR_TO_DATE(date,'%M.%d %Y') BETWEEN '2016-07-01' AND '2016-08-31';

Note: But date should be stored in a date datatype column. 注意:但是,日期应存储在date数据类型列中。 It's high time you converted the datatype to date of your date column. 这是你转换出的时间datatypedate您的date列。

In order to do that follow the steps below: 为此,请按照以下步骤操作:

ALTER TABLE Jobs
ADD new_date_column date;

UPDATE Jobs 
SET new_date_column = STR_TO_DATE(date,'%M.%d %Y');

ALTER TABLE Jobs DROP COLUMN `date`;

ALTER TABLE Jobs CHANGE COLUMN `new_date_column` `date` date;

Steps in a nut shell: 坚果壳中的步骤:

  1. Add a new column in Jobs table of type date . 在类型为date Jobs表中添加新列。

  2. Now update this new column with the values from your date column after converting to a valid date. 在转换为有效日期后,现在使用date列中的值更新此新列。

  3. You don't need that date column. 您不需要该date列。 So drop it. 放下

  4. Now rename the newly created column to date . 现在,将新创建的列重命名为date

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM