1

我有一个名为 stats 的表

player_id team_id match_date 进球助攻`  
        1 8 2010-01-01 1 1
        1 8 2010-01-01 2 0
        1 9 2010-01-01 0 5
  ...

我想知道一名球员何时达到里程碑(例如,100 个进球、100 次助攻、500 个进球……)
我还想知道一支球队何时达到里程碑。
我想知道哪个球员或球队达到100个进球第一,第二,第三......

我想使用带有表格的触发器来累积总数。
表 player_accumulator(和 team_accumulator)表将是

player_id total_goals total_assists
        1 3 6


team_id total_goals total_assists
      8 3 1
      9 0 5

每次在 stats 表中插入一行时,触发器都会插入/更新 player_accumulator 和 team_accumulator 表。
此触发器还可以验证玩家或团队是否已达到包含数字的里程碑表中的里程碑

里程碑
      100
      500
     1000
      ...

表 player_milestone 将包含玩家达到的里程碑:

player_id 统计里程碑日期
        1 目标 100 2013-04-02
        1 助攻 100 2012-11-19


有更好的方法来实现“里程碑”吗?
有没有触发器的最简单方法?

我正在使用 PostgreSQL

4

1 回答 1

3

我只计算得分的球员的所有进球和助攻,以及得分的球队。

像这样在客户端(伪代码):

function insert_stat(player_id, team_id, match_date, goals, assists)
{
  if (goals>0) {
    player_goals_before = query('select count(goal) from stats where player_id=?',player_id);
    team_goals_before = query('select count(goal) from stats where team_id=?',team_id);
  }
  if (assists>0) {
    player_assists_before = query('select count(assist) from stats where player_id=?',player_id);
    team_assists_before = query('select count(assist) from stats where team_id=?',team_id);
  }
  query("insert into stats (player_id, team_id, match_date, goal, assist)\n"
    +"values (?, ?, ?, ?, ?)", player_id, team_id, match_date, goal, assist);

  if (goals>0) {
    if ( has_milestone(player_goals_before+goals) and !has_milestone(player_goals_before) ) {
      alert("player " + player_id + " reached milestone!")
    }
    if ( has_milestone(team_goals_before+goals) and !has_milestone(team_goals_before) ) {
      alert("team " + team_id + " reached milestone!")
    }
  }
  // etc
}

Do not maintain milestone table, as this makes the database denormalized. I think this is a premature optimization. Only when the above is really not fast enough (for example when stats will have more than few thousands of rows per player_id or team_id) then you can think of maintaining milestone table.

于 2010-04-07T12:27:50.987 回答