我该如何处理这段关系?
How do I go about this relationship?
这里是SQL的新手。
我有这样的关系:
团队引用了所有 5 名成员,每个玩家都引用了他的团队。现在,我还应该将 teamPlayer1,2,... 设为 PLAYERS 实体的 FK 吗?因为到目前为止,我只处理过一个属性与另一个属性相对应的关系,而不是五比一。不知道该怎么做。
我建议您创建三个表:teams
、players
、team_players
。
Teams
create table teams (
id int not null auto_increment,
teamname varchar(100) not null,
country varchar(100) not null,
primary key (id)
);
Players
create table players (
id int not null auto_increment,
firstname varchar(100) not null,
lastname varchar(100) not null,
nickname varchar(100),
country varchar(100) not null,
fieldposition varchar(100), -- can be an int FK to a fieldpositions table
debutdate date,
primary key (id)
);
Team_players
create table team_players (
id int not null auto_increment,
teamid int not null,
playerid int not null,
primary key (id),
constraint uk_team_players_rel unique (teamid, playerid),
constraint fk_team_players_teamid foreign key (teamid) references teams (id),
constraint fk_team_players_playerid foreign key (playerid) references players (id)
);
示例 (MySQL):http://sqlfiddle.com/#!9/7c4ff8
teamPlayer1–5 是多余的,应该删除。您可以通过连接重建玩家列表。如果你想每队只允许五名球员,用 teamMember int, UNIQUE(teamId, teamMember), CHECK(teamMember between 0 and 4)
.
增加 PLAYERS
更正:您可以在没有加入的情况下重建每个团队的球员,因为所需的信息都在 PLAYERS table。
这里是SQL的新手。
我有这样的关系:
团队引用了所有 5 名成员,每个玩家都引用了他的团队。现在,我还应该将 teamPlayer1,2,... 设为 PLAYERS 实体的 FK 吗?因为到目前为止,我只处理过一个属性与另一个属性相对应的关系,而不是五比一。不知道该怎么做。
我建议您创建三个表:teams
、players
、team_players
。
Teams
create table teams (
id int not null auto_increment,
teamname varchar(100) not null,
country varchar(100) not null,
primary key (id)
);
Players
create table players (
id int not null auto_increment,
firstname varchar(100) not null,
lastname varchar(100) not null,
nickname varchar(100),
country varchar(100) not null,
fieldposition varchar(100), -- can be an int FK to a fieldpositions table
debutdate date,
primary key (id)
);
Team_players
create table team_players (
id int not null auto_increment,
teamid int not null,
playerid int not null,
primary key (id),
constraint uk_team_players_rel unique (teamid, playerid),
constraint fk_team_players_teamid foreign key (teamid) references teams (id),
constraint fk_team_players_playerid foreign key (playerid) references players (id)
);
示例 (MySQL):http://sqlfiddle.com/#!9/7c4ff8
teamPlayer1–5 是多余的,应该删除。您可以通过连接重建玩家列表。如果你想每队只允许五名球员,用 teamMember int, UNIQUE(teamId, teamMember), CHECK(teamMember between 0 and 4)
.
更正:您可以在没有加入的情况下重建每个团队的球员,因为所需的信息都在 PLAYERS table。