/* Query to select last 6 months (to the day) */
SELECT
*
FROM
test_dates
WHERE
`date` > date_add(curdate(), INTERVAL -6 MONTH)
/* Query to get every date from 01/01/2018 to 06/25/2018 */
SELECT
`date`
FROM
test_dates
WHERE
STR_TO_DATE(CONCAT(YEAR(`date`), '-', MONTH(`date`), '-01'), '%Y-%m-%d')
>=
STR_TO_DATE(
CONCAT(
YEAR(DATE_ADD(curDate(), INTERVAL -5 MONTH)),
'-',
MONTH(DATE_ADD(curDate(), INTERVAL -5 MONTH))
, '-01'
)
, '%Y-%m-%d'
);
我用来设置测试的代码:
/* Create a table to test */
DROP TABLE IF EXISTS test_dates;
CREATE TABLE IF NOT EXISTS test_dates (
`date` datetime
);
/* Insert Test Dates */
INSERT INTO test_dates (`date`) VALUES ('2018-06-01');
INSERT INTO test_dates (`date`) VALUES ('2018-05-01');
INSERT INTO test_dates (`date`) VALUES ('2018-04-01');
INSERT INTO test_dates (`date`) VALUES ('2018-03-01');
INSERT INTO test_dates (`date`) VALUES ('2018-02-01');
INSERT INTO test_dates (`date`) VALUES ('2018-01-01');
INSERT INTO test_dates (`date`) VALUES ('2017-012-01');
INSERT INTO test_dates (`date`) VALUES ('2017-011-01');
1条答案
按热度按时间j8ag8udp1#
使用日期添加功能。参见以下示例:
我用来设置测试的代码: