sql - 德州扑克数据的关系数据库结构

标签 sql mysql ruby-on-rails activerecord associations

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

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

这有意义吗?

最佳答案

如果您打算使用 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 语句来确保您在使用它们时会遇到索引。如果您加载数百万条记录,表格扫描将非常痛苦,而且在这样的游戏中这不会花费很长时间,因为单手涉及数十个 Action ,而且通常每小时玩数十手。

关于sql - 德州扑克数据的关系数据库结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3692484/

相关文章:

php - 插入相关表mysql

MySQL。一段时间内未售出的产品

sql - postgresql查询多个相同的表

php - 准备好的查询中的可选参数

java - 从 JPA 类自动创建表

mysql - Rails 无法删除或更新父行 : a foreign key constraint fails

ruby-on-rails - 使用 PostgreSQL 使用 ActiveRecord 准备和执行语句

jquery - Ajax自动完成url问题

mysql - 当我搜索 'û'时,选择查询mysql结果 'u'出现

html - 未显示 Logo 背景图像(Rails 应用程序)