I have a very old database I made when I was still learning PHP and 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):
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
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
Now use this in your query to search for result having dates between 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. It's high time you converted the datatype
to date
of your date
column.
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:
Add a new column in Jobs
table of type date
.
Now update this new column with the values from your date
column after converting to a valid date.
You don't need that date
column. So drop it.
Now rename the newly created column to date
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.