3

我需要显示今天下周五DATE之间的表格中的所有数据,

为此,我运行了一个查询:

Select * 
FROM table 
WHERE

  date_row BETWEEN now()+1 
  and DATE_ADD(now(), INTERVAL 
    (9 - IF(DAYOFWEEK(CURDATE())=5, 8, DAYOFWEEK(now()))) DAY)

Result set 不返回Next Friday的数据。

4

1 回答 1

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 )

如果你的意思是说你想要下周的 Friday而不是下一个 Friday,那么 Friday 和 Saturday 是一样的,但其他日子是 (7 + (6 - today's weekday))

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 )
  )
于 2012-06-09T13:04:59.093 回答