仅按月和日比较日期

时间:2012-01-29 19:24:16

标签: mysql date

我的date表格中有foos字段。所以现在我需要从日期间隔中选择所有foos,但只比较月和日。

例如,我需要在7 Jan 2012之前和之后10天选择所有foos - > 28 Dec - 17 Jan。或者周围10 Jul 2009 - > 3 Jul - 17 Jul。它应该仅根据所有年份的月份和日期进行选择。

我的原始和天真的解决方案

SELECT b_date FROM foos 
  WHERE DAYOFYEAR(b_date) BETWEEN 
    DAYOFYEAR('2011-01-07' - INTERVAL 10 DAY) AND (DAYOFYEAR('2011-01-07' - INTERVAL 10 DAY) + 20)
  OR DAYOFYEAR(b_date) BETWEEN 
    (DAYOFYEAR('2011-01-07' + INTERVAL 10 DAY) - 20) AND DAYOFYEAR('2011-01-07' + INTERVAL 10 DAY)
  GROUP BY foos.id;

2 个答案:

答案 0 :(得分:2)

如果您想查找所有日期日期28 Dec 201117 Jan 2012,可以使用以下内容:

WHERE DateColumn BETWEEN '2012-01-07' - INTERVAL 10 DAY
                     AND '2012-01-07' + INTERVAL 10 DAY

对于更普遍的问题,我看到了两种方法。一个易于编写,但可能很慢,有一个大的foos表:

SELECT f.*
FROM 
      foos AS f
  CROSS JOIN
      ( SELECT 32 * MONTH(StartDate) + DAY(StartDate)
                 AS StartCheck
             , 32 * MONTH(EndDate) + DAY(EndDate)
                 AS EndCheck 
        FROM
            ( SELECT ('2012-01-07' - INTERVAL 10 DAY) AS StartDate 
                   , ('2012-01-07' + INTERVAL 10 DAY) AS EndDate 
            ) AS c
      ) AS cc
WHERE 32*MONTH(f.DateColumn)+DAY(f.DateColumn) BETWEEN StartCheck 
                                                   AND EndCheck 
   OR  StartCheck > EndCheck 
   AND 32*MONTH(f.DateColumn)+DAY(f.DateColumn) NOT BETWEEN EndCheck + 1
                                                        AND StartCheck - 1 

答案 1 :(得分:1)

SELECT b_date FROM foos 
  WHERE DAYOFYEAR(b_date) BETWEEN 
    DAYOFYEAR('2011-01-07' - INTERVAL 10 DAY) AND (DAYOFYEAR('2011-01-07' - INTERVAL 10 DAY) + 21)
  OR DAYOFYEAR(b_date) BETWEEN 
    (DAYOFYEAR('2011-01-07' + INTERVAL 10 DAY) - 21) AND DAYOFYEAR('2011-01-07' + INTERVAL 10 DAY)
  GROUP BY foos.id;