0

我需要计算给定一周之后的周数。这对于一年中的大多数星期来说都是微不足道的,但在年底/年初却不是这样。例如,如果我需要知道 2013 年第 52 周之后的一周。

我想使用defaul_week_format 3,即a)周从星期一(而不是星期日)开始b)一年内的编号从1(而不是0)开始,c)第1周是第一周超过今年3天。

例如,我计算 2014 年第 36 周后一周的方法如下:

SELECT WEEK(DATE_ADD(STR_TO_DATE('W36 2014 Tuesday', 'W%V %X %W'), INTERVAL 1 WEEK))

对于这个例子,我计算第 36 周星期二的日期,加上一周,然后计算这一天的星期几。这会起作用,但即使不增加一周,我也会有这种奇怪的行为:

它适用于 default_week_format 0:

SET @@local.default_week_format=0;
SELECT STR_TO_DATE('W36 2014 Tuesday', 'W%V %X %W');
-> Tuesday of week 36 is 2014-09-09
SELECT week('2014-09-09');
-> 2014-09-09 is in week 36

到目前为止,一切都很好:第 36 周的星期二是第 36 周。

但是这个简单的实验不适用于 default_week_format 3:

SET @@local.default_week_format=3;
SELECT STR_TO_DATE('W36 2014 Tuesday', 'W%V %X %W');
-> Tuesday of week 36 is 2014-09-09
-> This is wrong, because numbering should start with 1 (instead of 0 now)!
-> Tuesday of week 36 should be 2014-09-02
SELECT week('2014-09-09');
-> 2014-09-09 is in week 37

所以 MySQL 告诉我第 36 周的星期二是第 37 周!

我对此的唯一解释:

  • week() 将 default_week_format 考虑在内
  • str_to_date() 忽略 default_week_format

如何强制 MySQL 函数 str_to_date 使用 default_week_format?

或者:我还能如何计算下一周的数量?我也可以用 PHP 来做,但是我从 MySQL 数据库中得到了几周的数字。

谢谢你的帮助!

4

2 回答 2

1

I was facing exactly the same problem. My solution - perhaps not the greatest one, but it works.

As you already mentionned: Most of the cases are trivial, you just need to know the year end / beginning. Therefore, I just store the relevant weeks for the needed number of years in the following table:

CREATE TABLE `NEXT_WEEK_TAB` (
  `CUR_WEEK`  varchar(8) NOT NULL,
  `NEXT_WEEK` varchar(8) NOT NULL,
  PRIMARY KEY (`CUR_WEEK`,`NEXT_WEEK`)
)

You get the following week now with the current algorithm:

following_week = (SELECT next_week 
                  FROM   next_week_tab 
                  WHERE  cur_week = <your_current_week>);
if !following_week then following_week++;

As I said: Probably not the nicest solution, but it's pretty simple - and it works.

于 2014-02-11T21:24:33.807 回答
0

我认为您必须将 Week 与 mode 参数一起使用

mysql> SELECT WEEK('2008-02-20',0);
        -> 7
mysql> SELECT WEEK('2008-02-20',1);
        -> 8

看看这里: http ://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_week

于 2014-02-10T23:10:16.670 回答