我需要选择接下来45天内(与年份无关)的所有日期(日期和月份)。以下查询已停止工作。就像在确实有数据的时候从字面上开始不返回任何行一样。
还有另一种方法可以执行此查询吗?如果需要,很高兴在php循环中检查记录。
从本质上讲,即使一年过去了,我也需要显示接下来45天内的所有记录。
SELECT
p.*,
c.company
FROM
products p
LEFT JOIN
customers c
ON c.id = p.id
WHERE
DATE_FORMAT(p.service_date, '%m-%d') >= DATE_FORMAT(CURDATE(), '%m-%d')
AND DATE_FORMAT(p.service_date, '%m-%d') <= DATE_FORMAT((CURDATE() + INTERVAL 45 DAY), '%m-%d')
AND c.email_service = 1
ORDER BY
p.service_date ASC
答案 0 :(得分:1)
使用php解决了这个问题
// Get the dates m-d for the next 45 days
for ($i = 0; $i <= 45; $i++) {
$days = '+' . $i . ' days';
$date = date('m-d', strtotime($days));
if ($i != 45) {
$DateQuery .= "'$date',";
} else {
$DateQuery .= "'$date'";
}
}
并将需要的日期直接插入查询中
SELECT
p.*,
c.company
FROM
products p
LEFT JOIN
customers c
ON c.id = p.id
WHERE
DATE_FORMAT(p.service_date, '%m-%d') IN
(
$DateQuery
)
AND c.email_service = 1
ORDER BY
p.service_date ASC
答案 1 :(得分:0)
我不知道您原来的查询为什么要利用已经存储在MySQL Date类型中的列(Date_Format()
)上的service_date
进行范围比较。它也不能使用任何索引(如果已定义)。
您只需要在日期上加上/减去Interval
:
SELECT
p.*,
c.company
FROM
products p
LEFT JOIN
customers c
ON c.id = p.id
WHERE
p.service_date >= CURDATE()
AND p.service_date <= (CURDATE() + INTERVAL 45 DAY)
AND c.email_service = 1
ORDER BY
p.service_date ASC
答案 2 :(得分:0)
解决此问题的最佳方法是使用DAYOFYEAR
。困难的部分是当您在年末的45天之内处理这种情况,在这种情况下,您必须拆分支票以查看日期是在现在到年末还是在年初之间现在+ 45天;否则,您只需检查一年中的日期是否介于现在和现在之间+ 45天之间。尝试用以下方法代替您的病情:
CASE WHEN DAYOFYEAR('2018-12-31')-DAYOFYEAR(NOW()) < 45 THEN
DAYOFYEAR(p.service_date) BETWEEN DAYOFYEAR(NOW()) AND DAYOFYEAR('2018-12-31') OR
DAYOFYEAR(p.service_date) BETWEEN 1 AND DAYOFYEAR(NOW() + INTERVAL 45 DAY)
ELSE
DAYOFYEAR(p.service_date) BETWEEN DAYOFYEAR(NOW()) AND DAYOFYEAR(NOW() + INTERVAL 45 DAY)
END
您的完整查询应如下所示:
SELECT
p.*,
c.company
FROM
products p
LEFT JOIN
customers c
ON c.id = p.id
WHERE
(CASE WHEN DAYOFYEAR('2018-12-31')-DAYOFYEAR(NOW()) < 45 THEN
DAYOFYEAR(p.service_date) BETWEEN DAYOFYEAR(NOW()) AND DAYOFYEAR('2018-12-31') OR
DAYOFYEAR(p.service_date) BETWEEN 1 AND DAYOFYEAR(NOW() + INTERVAL 45 DAY)
ELSE
DAYOFYEAR(p.service_date) BETWEEN DAYOFYEAR(NOW()) AND DAYOFYEAR(NOW() + INTERVAL 45 DAY)
END)
AND c.email_service = 1
ORDER BY
p.service_date ASC
如果您担心leap年,可以将DAYOFYEAR('2018-12-31')
更改为DAYOFYEAR(CONCAT(YEAR(NOW), '-12-31'))