SQL - 在循环中添加日期到日期

时间:2017-03-29 22:37:15

标签: mysql sql phpmyadmin

我有一个包含此字段的表格:

Id int(11) pk, 
Start_date date, 
End_date date, 
type tinyint(1),
Frequency int. 

我想在这个表上选择start_date + frequency = @date(变量日期),直到end_date(循环)。

这怎么用sql?

提前致谢。

编辑: 变量日期是(例如):

SET @date = '2017-03-30'

类型可以是0或1:

  • 如果type = 0,我的查询是:

     select * from table 
     where type = 0 and start_date <= @date AND end_date>=@date
    
  • 如果type = 1,则frequency是具有整数(天数间隔)的字段。所以我必须检查将此值添加到start_date是否等于@date。

    • 如果是,我必须返回当前记录
    • 如果不是,我必须重复此操作

      Date current = start_date + interval of 'frequency' days
      while(current < end_date){
      if(current == @date)
      (this is the record I want)
      else
      current+=frequency
      }
      

类型1的查询结果可以是多个记录。最后我想UNION在唯一选择中输入类型0和1的结果。

1 个答案:

答案 0 :(得分:1)

看起来像你想要的东西:

select * from table 
where
   start_date <= @date AND
   end_date>=@date AND
   (
     type = 0 OR
     (
        type = 1 AND
        mod(datediff(@date,start_date),frequency) = 0
     )
   )