将频率表转换为mySQL中的调度视图

时间:2014-02-24 20:35:16

标签: mysql schedule

我有一个带有下一个内容的mySQL表:

 ID   START        FREQUENCY  REPETITIONS  RESOURCE 
 --------------------------------------------------
 1    24/02/2014   daily      5            10
 2    24/02/2014   yearly     2            11

有没有简单的方法将其转换为视图,例如:

ID  DATE         RESOURCE
-------------------------
1   24/02/2014   10
1   25/02/2014   10
1   26/02/2014   10
1   27/02/2014   10
1   28/02/2014   10
2   24/02/2014   11
2   24/02/2015   11

由于

1 个答案:

答案 0 :(得分:0)

如果您可以重复次数有限,则可以创建一个Numbers表格,如下所示:

CREATE TABLE numbers (
  num INT,
  i INT
);

INSERT INTO numbers VALUES
(1,1),
(2,1),
(2,2),
(3,1),
(3,2),
(3,3),
(4,1),
(4,2),
(4,3),
(4,4),
...

然后你可以使用JOIN:

SELECT
  ID,
  `START` + INTERVAL CASE WHEN FREQUENCY='daily' THEN i-1 ELSE 0 END DAY
          + INTERVAL CASE WHEN FREQUENCY='yearly' THEN i-1 ELSE 0 END YEAR
   as `Date`,
  RESOURCE
FROM
  yourtable INNER JOIN numbers
  ON yourtable.REPETITIONS = numbers.num
ORDER BY
  ID, numbers.i

请参阅小提琴here