I have a primary key for a table "December 13, 2017 - December 25, 2017" which is stored as a varchar.
What do I query so that I get a list of results from a search entry like January - December 2017?
I have a primary key for a table "December 13, 2017 - December 25, 2017" which is stored as a varchar.
What do I query so that I get a list of results from a search entry like January - December 2017?
Convert your varchar into 2 columns like startDate and endDate in your mysql table.
var str = "December 13, 2017 - December 25, 2017"; var arr = str.split('-');
var startDate = new Date(arr[0]); var endDate = new Date(arr[1]);
If you store these into your database, it is easy to write queries in sql.
You can store them as separate dates like so:
CREATE TABLE
`dates`
(
`date_id` INT PRIMARY KEY AUTO_INCREMENT,
`start_date` DATE,
`end_date` DATE
);
INSERT INTO
`dates`
(`start_date`, `end_date`)
VALUES
('2017-12-13', '2017-12-25');
Then if you want to query based on the range, you could do something like:
SELECT
DATE_FORMAT(`start_date`, '%M %d, %Y') AS `start_date`,
DATE_FORMAT(`end_date`, '%M %d, %Y') AS `end_date`
FROM
`dates`
WHERE
`start_date` BETWEEN '2017-01-01' AND '2017-12-31';
Which provides:
start_date | end_date
-------------------------------------------
December 13, 2017 | December 25, 2017
Now... to get there, you have to parse the existing records, so assuming a table:
CREATE TABLE
`fixme`
(
`date_id` VARCHAR(50)
);
INSERT INTO
`fixme`
VALUES
('December 13, 2017 - December 25, 2017');
You can split them into dates and insert them into the new table:
SELECT
STR_TO_DATE(SUBSTRING_INDEX(`date_id`, ' - ', 1),'%M %d, %Y') AS `start_date`,
STR_TO_DATE(SUBSTRING(`date_id`, LOCATE(' - ', `date_id`)+2),'%M %d, %Y') AS `end_date`
FROM
`fixme`;
Results in:
start_date | end_date
----------------------
2017-12-13 | 2017-12-25
SQL Fiddle: http://sqlfiddle.com/#!9/4101cd/7