【问题标题】:Storing daily statistics in relational database在关系数据库中存储每日统计信息
【发布时间】:2015-02-16 19:43:53
【问题描述】:

我正在创建一个游戏,它需要每天保存每个玩家的统计数据(玩过的游戏、获得的经验和金币、当前的金币)以及历史数据。

我目前的做法是我有 3 张桌子:

table `stats_current` -> for storing player's stats on CURRENT DAY
player_id | games_played | gold_earned | current_gold

table `stats_all_time` -> player's stats accumulated from the very beginning
player_id | games_played | gold_earned | current_gold

table `stats_history` -> player's stats daily, one record for one day
player_id | date | games_played | gold_earned | current_gold

每个玩家在stats_current 有一条记录,在stats_all_time 有一条记录,在stats_history 表上的记录有限(例如,仅记录最近 30 天)。

然后有一个守护进程/cron 作业每天执行这些操作:

  • 对于每个玩家:
  • stats_current上搜索其记录,获取值。
  • 将新记录插入stats_history,值来自stats_current
  • 更新stats_all_time 上的记录,使用stats_current 中的值递增其值
  • stats_current 上,将games_playedgold_earned 的值重置为0。但保持current_gold 不变。

常见任务的解决方案:

  • 获取玩家 X 当前的金币:stats_current 检索 current_gold
  • 获取玩家X最近7天的统计数据:选择stats_history中的6条记录,加上stats_current中的今天记录
  • 获取玩家 X 的总游戏数:stats_history 检索值

问题:

  • 这是一种可行的方法吗?
  • 有哪些弱点?
  • 有没有办法优化这个解决方案?

【问题讨论】:

    标签: database statistics relational-database


    【解决方案1】:

    您的方法未能利用 SQL 的强大功能

    stats_history 要获取今天的统计数据,只需使用

    SELECT * FROM stats_history WHERE Date = CURDATE() and PlayerId = PlayerId--Depending on your RDBMS you might need a different function to get the date.
    

    要获取所有时间统计数据,只需使用

    SELECT SUM(games_played) as games_played, SUM(gold_earned) as gold_earned FROM stats_history WHERE PlayerId = playerid 
    

    您可以通过从 stats_history 中为该玩家选择最高记录,或使用任何其他 RMDBS 特定策略(SQL Server 的 Over 子句、按日期排序结果集和 MySQL 添加 current_gold等等)

    您的方法是有风险的,因为如果您的 Chron 失败,其他两个表将不准确。这也是不必要的数据重复。

    【讨论】:

      猜你喜欢
      • 2015-11-10
      • 1970-01-01
      • 2010-10-27
      • 2010-12-22
      • 2012-07-15
      • 1970-01-01
      • 1970-01-01
      • 2012-06-15
      • 2013-01-04
      相关资源
      最近更新 更多