Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

sql - Is this normalization correct? (two many-to-manys connected by a many-to-one)

I have a schema for a scorekeeping database with Game, Team, Player tables.

One team has many players, each player has only one team. Each team plays many games, each game has many teams. In each game, players score a certain number points individually and as a team - this maps to a player_score and a team_score. A team's total score for a game is the sum of all of its players player_score for that game and the team's team_score for that game.

This is my plan -

GameTeam table includes the team's team_score for that game, and has foreign keys of Game.id and Team.id. Many to many.

GamePlayer table includes the player's player_score for that game, and has foreign keys of Game.id and Player.id. Many to many.

So the problem is that GameTeam and GamePlayer aren't linked and it seems like they should be - since a player always belongs to one team. My solution was to add a one-to-many relationship between GameTeam and GamePlayer, then if I have a game id and a team id I can search for a GameTeam where those match, iterate over all the gameTeam.gamePlayers adding each player_score, add on the team_score at the end, and calculate total_score.

Does this make sense? Am I completely off? Any help appreciated, thanks. If it matters, I'm using SQLAlchemy.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem to your design is that you have used surrogate identifier as the primary key for the tables, a well defined primary key will solve the problem:

Team   -> pk:team_id
Player -> pk:player_id
TeamPlayer -> pk:{team_id + player_id}

Game   -> pk:game_id
GameTeam -> pk:{game_id + team_id}
GamePlayer -> pk:{game_id + GameTeam_pk + TeamPlayer_pk} 
              = {game_id + {game_id + team_id} + {team_id + player_id} }

Having check constraints on GamePlayer will help the problem:

GamePlayer 
{
 Check game_id (FK of Game) = game_id (FK of GameTeam );
 Check team_id (FK of GameTeam) = team_id (FK of TeamPlayer);
}

So
player_score will be property of GamePlayer.
team_score will (may) be SUM of GamePlayer.player_score with specific team_id.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...