哪个SQL表结构更适合按月存储数据?

时间:2015-02-23 18:23:09

标签: mysql sql

我将按月将数据存储到数据库表中,并且我想知道哪种表结构最好。

对于它的价值,我将使用MySQL并且更愿意使用选项1.

选项1 - (我认为这是规范化)

month_id - tinyint unsigned
value - int unsigned

选项2 - 每个表字段存储1个月

january - int unsigned
february - int unsigned
march - int unsigned
(etc to December.)

1 个答案:

答案 0 :(得分:1)

选项1.

如果您需要超过一年的话,这很容易扩展。

然后,如果您需要其他格式的数据,您可以使用:

Select 
  sum(case month_id when 1 then Value end) as January,
  sum(case month_id when 2 then Value end) as February,
  sum(case month_id when 3 then Value end) as March,
  sum(case month_id when 4 then Value end) as April,
  sum(case month_id when 5 then Value end) as May,
  sum(case month_id when 6 then Value end) as June,
  sum(case month_id when 7 then Value end) as July,
  sum(case month_id when 8 then Value end) as August,
  sum(case month_id when 9 then Value end) as September,
  sum(case month_id when 10 then Value end) as October,
  sum(case month_id when 11 then Value end) as November,
  sum(case month_id when 12 then Value end) as December
from MonthlyData