从计划数据创建时间表视图

时间:2017-01-23 12:45:33

标签: mysql database-design pivot

目前,我正在使用SET LC_TIME = lang or DEFAUT; PHP中的Codeigniter框架开发时间表程序。我有MySQL表,其中包含以下数据:

schedule

我可以将+-------------+--------------+-----------+--------+ | Schedule ID | Subject Name | Day | Period | +-------------+--------------+-----------+--------+ | 1 | Biology | Monday | 1 | | 2 | Biology | Wednesday | 2 | | 3 | Biology | Friday | 3 | | 4 | Physics | Tuesday | 8 | | 5 | Physics | Thursday | 6 | | 6 | Math | Monday | 7 | +-------------+--------------+-----------+--------+ 表的每一行作为数组。我想在以下视图中创建一个时间表(使用schedule表):

HTML

对于以上述格式创建表格,我将不胜感激。

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT ScheduleID,
       MAX(CASE WHEN Day = 'Monday' THEN SubjectName END) AS Monday,
       MAX(CASE WHEN Day = 'Tuesday' THEN SubjectName END) AS Tuesday,
       MAX(CASE WHEN Day = 'Wednesday' THEN SubjectName END) AS Wednesday,
       MAX(CASE WHEN Day = 'Thursday' THEN SubjectName END) AS Thursday,
       MAX(CASE WHEN Day = 'Friday' THEN SubjectName END) AS Friday
FROM mytable
GROUP BY ScheduleID

Demo here

修改

您似乎想要按Period而不是ScheduleID进行分组。您可以创建一个包含所有可能Period值的内联表,或者如果您已有一个查找表,则使用查找表:

SELECT t1.Period,
       MAX(CASE WHEN Day = 'Monday' THEN SubjectName END) AS Monday,
       MAX(CASE WHEN Day = 'Tuesday' THEN SubjectName END) AS Tuesday,
       MAX(CASE WHEN Day = 'Wednesday' THEN SubjectName END) AS Wednesday,
       MAX(CASE WHEN Day = 'Thursday' THEN SubjectName END) AS Thursday,
       MAX(CASE WHEN Day = 'Friday' THEN SubjectName END) AS Friday 
FROM (SELECT 1 AS Period 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) AS t1
LEFT JOIN mytable AS t2 ON t1.Period = t2.Period
GROUP BY t1.Period

Demo here