我需要显示表格中的所有数据,其中今天与下周五之间有DATE
,
为此,我运行了一个查询:
Select *
FROM table
WHERE
date_row BETWEEN now()+1
and DATE_ADD(now(), INTERVAL
(9 - IF(DAYOFWEEK(CURDATE())=5, 8, DAYOFWEEK(now()))) DAY)
结果集未返回下周五的数据。
答案 0 :(得分:1)
MySQL从1(星期日)开始。使用CURDATE()
代替NOW()
来截断时间部分,这样您就只能处理日期并调用DATE(date_row)
来截断日期。
如果今天是星期五,请加7天。如果今天不是星期五而是星期五之前,请加上(6 - 今天的工作日)。如果今天是星期六,请加6天。
WHERE
DATE(date_row) BETWEEN CURDATE() AND
DATE_ADD(CURDATE(), INTERVAL (
/* It's Friday, add 7 */
IF(DAYOFWEEK(CURDATE())=6, 7,
/* It's Saturday, add 6 */
IF(DAYOFWEEK(CURDATE())=7, 6,
/* All other days, add 6 - weekday */
(6 -DAYOFWEEK(CURDATE())))))
DAY )
如果你的意思是说你希望星期五下周五而不是下周五,那么星期五和星期六是相同的,但其他日子是(7 + (6 - 今天的工作日))
WHERE
DATE(date_row) BETWEEN CURDATE() AND
DATE_ADD(CURDATE(), INTERVAL (
/* It's Friday, add 7 */
IF(DAYOFWEEK(CURDATE())=6, 7,
/* It's Saturday, add 6 */
IF(DAYOFWEEK(CURDATE())=7, 6,
/* All other days, add 6 - weekday + 7*/
(7 + (6 -DAYOFWEEK(CURDATE()))))))
DAY )
然后你可以在没有IF()
逻辑的情况下简化它,因为星期五6 + 7 +(6-6)= 7,星期六7 + 7 + 6 - 7 = 6。
WHERE
DATE(date_row) BETWEEN CURDATE() AND
DATE_ADD(CURDATE(), INTERVAL (7 + (6 - DAYOFWEEK(CURDATE()))) DAY)
如果您今天不想在今天星期五返回,则无法在CURDATE()
中使用BETWEEN
。如果是星期五,请添加OR
条件以执行。
WHERE
/* If today is Friday, exclude today, and start counting tomorrow */
(DAYOFWEEK(CURDATE()) = 6
AND DATE(date_row) BETWEEN DATE_ADD(CURDATE(), INTERVAL 1 DAY) AND DATE_ADD(CURDATE(), INTERVAL 7 DAY)
)
OR (
DATE(date_row) BETWEEN CURDATE() AND
DATE_ADD(CURDATE(), INTERVAL (
/* It's Saturday, add 6 */
IF(DAYOFWEEK(CURDATE())=7, 6,
/* All other days, add 6 - weekday + 7*/
(7 + (6 -DAYOFWEEK(CURDATE())))))
DAY )
)