MySQL自动生成所有可能的组合作为行

时间:2014-01-02 05:44:46

标签: php mysql

我有3个表Channels,DateSelection和History。 Channels和DateSelection根据需要进行更新,通常如下所示 频道表格 -

  CHID    CHNAME    CHLOC                     

  1        BARRY     NULL                           

  2        TOM       NULL

  3        SHIRLY    NULL

DateSelection

WEEKCOMMENCING       WEEKENDING

  01/01/2014        03/01/2014

历史记录列为空 - 频道 - 日期 - 用户

我想要做的是运行一个查询或触发mysql或php等会产生行

Channel   -    Date    -     User

  Barry         01/01/2014

  Barry         02/01/2014

  Barry         03/01/2014

  Tom           01/01/2014

  Tom           02/01/2014

  Tom           03/01/2014

 Shirly         01/01/2014

 Shirly         02/01/2014

 Shirly         03/01/2014

基本上每种可能的组合?

我在视图中使用了以下内容。并独立地做每一天

INSERT INTO FCHISTORY

(CHNAME,DATE)

SELECT Channels.CHNAME,FCCURRENTDATES.DATE

FROM频道

CROSS JOIN FCCURRENTDATES

然而,这会不断产生重复。我可以添加的内容只有CHNAME和DATE的每个匹配组合中的一个

有人可以帮助我吗?我不介意一天一次地做这件事,但实际上有一百个频道。谢谢!

1 个答案:

答案 0 :(得分:1)

这应该可以解决问题:

SELECT CHNAME AS Channel, a.Date, '' AS User
FROM Channels c
JOIN DateSelection ds
JOIN (
  select curdate() + INTERVAL 100 DAY - INTERVAL (a.a + (10 * b.a) + (100 * c.a)) DAY as Date
  from (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as a
  cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as b
  cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as c
) a ON a.Date BETWEEN ds.WEEKCOMMENCING AND ds.WEEKENDING
ORDER BY CHID, a.Date

请参阅sqlfiddle - http://sqlfiddle.com/#!2/87a5f/19

请注意,您可以调整日期范围以进行选择,具体取决于您是在展望未来还是过去。现在范围是曲线前900天和100天后。根据需要进行调整。