【问题标题】:Relational database structure for Texas Hold'em poker data德州扑克数据的关系数据库结构
【发布时间】:2010-09-11 20:09:04
【问题描述】:

我正在计划一个关系数据库来存储扑克游戏数据(例如将包含在手牌历史中的数据)。我想帮助弄清楚如何设计关联。似乎应该有 4 个模型:游戏、手牌、玩家和动作(给定玩家的单个动作,如加注、弃牌、跟注)。让我列出我所拥有的:

class Game < ActiveRecord::Base
  has_many :hands
  has_many :actions
  has_and_belongs_to_many :players
end

class Hand < ActiveRecord::Base
  has_many :actions
  belongs_to :game
  has_and_belongs_to_many :players
end

class Action < ActiveRecord::Base
  belongs_to :game
  belongs_to :hand
  belongs_to :player
end

class Player < ActiveRecord::Base
  has_and_belongs_to_many :games
  has_and_belongs_to_many :hands
  has_many :actions
end

这有意义吗?

【问题讨论】:

    标签: sql mysql ruby-on-rails activerecord associations


    【解决方案1】:

    如果您打算使用has_and_belongs_to_many,您可能应该改用has_many ..., :through,因为它更易于管理。您已经有了一个 Action 模型,它可以满足您的需要,而无需创建一些连接表:

    class Game < ActiveRecord::Base
      has_many :hands
    end
    
    class Hand < ActiveRecord::Base
      has_many :actions
      belongs_to :game
    
      has_many :players,
        :through => :actions,
        :source => :player
    end
    
    class Action < ActiveRecord::Base
      belongs_to :game
      belongs_to :hand
      belongs_to :player
    end
    
    class Player < ActiveRecord::Base
      has_many :actions
      has_many :played_games,
        :through => :actions,
        :as => :game
      has_many :played_hands,
        :through => :actions,
        :as => :hand
    end
    

    通常,查询中涉及的表越少,它们运行的​​速度就越快。涉及任何类型的JOIN 都会导致无法预测的查询性能。

    请务必仔细为您的表建立索引,并使用EXAMINE 语句确保您在使用它们时会遇到索引。如果您加载数百万条记录,则表格扫描将非常痛苦,而在像这样的游戏中不会花费很长时间,因为单手涉及数十个动作,并且通常每小时玩数十手。

    【讨论】:

    • 嗨 Tadman,感谢您的帮助 - 这非常有用。我了解您如何设置 Game、Hand 和 Action 模型,但我仍然对 Player 模型有点不清楚。您能否解释一下 Player 表的外观(即包含哪些外键)?是不是有一个played_hands 列,里面有hand_id 值?另外,你介意解释一下为什么游戏只与手有关吗?再次感谢您的帮助!
    • 如果您点击链接(如game.hands.first.players)或创建您自己的自定义查询以更有效地加入该链接,您可以从游戏导航到播放器。此外,has_many ..., :through 关系不涉及新列,它将通过利用现有关系来工作。在您给出的示例中,players 表只需要一个 id 列即可工作,其余的取决于您。动作是定义所有关系的地方。
    【解决方案2】:

    作为初稿有意义。由您所拥有的内容产生的关联给出了以下表格和键:

    Game       :: Game_id (PK);....
    Hand       :: Hand_id (PK); Game_id (FK);....
    Player     :: Player_id (PK); Action_id (FK);
    ActionType :: ActionType_id (PK); Type;
    (Note this table will only have three records - raise, fold, call)
    Action     :: Action_id (PK); ActionType_id (FK); Game_id (FK); Hand_id (FK); Player_id (FK);....
    PlayerHand :: Player_id (FK); Hand_id (FK); Has_or_Belongs; (PK is (Player_id, Hand_id))
    GamePlayer :: Game_id (FK); Player_id (FK); Has_or_Belongs; (PK is (Game_id, Player_id))
    

    【讨论】:

    • 使用整数或枚举对ActionType进行分类会更好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 2012-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多