使用具有多个表的外键

时间:2017-05-06 00:09:37

标签: sql

我在创建数据库时遇到问题。我的虚构问题是创建用于跟踪排球比赛的数据库。它应该包含有关球员的信息(他们参加的球队,一名球员只能在一支球队中比赛),以及参加比赛(每场比赛每队包含6名球员)。

我想创建以下表格:

  • 玩家(Id P,姓名,姓氏,Team_Name F);
  • 团队(Team_Name P,Coach);
  • 游戏(日期,Team1 F,Team2 F,Player1_Team1 F,... Player2_Team2 F,Player1_Team2 F,...,Player2_Team2 F)。

我希望Team1和Team2是Team表中的外键Team_Name。这是我的尝试,我得到的外键不正确。我很乐意帮忙。

CREATE TABLE Team (
    Team_Name varchar(20)  NOT NULL,
    Coach varchar(20)  NOT NULL,
    CONSTRAINT Team_pk PRIMARY KEY (Team_Name)
);


CREATE TABLE Game (
    id int  NOT NULL,
    Data date NOT  NULL,
    Team1 varchar(20)   NOT NULL,
    Team2 varchar(20)  NOT NULL,
    Score int  ,
    D1_Player1 int  NOT NULL,
    D1_Player2 int  NOT NULL,
    D1_Player3 int  NOT NULL,
    D1_Player4 int  NOT NULL,
    D1_Player5 int  NOT NULL,
    D1_Player6 int  NOT NULL,
    D2_Player1 int  NOT NULL,
    D2_Player2 int  NOT NULL,
    D2_Player3 int  NOT NULL,
    D2_Player4 int  NOT NULL,
    D2_Player5 int  NOT NULL,
    D2_Player6 int  NOT NULL,
    CONSTRAINT Game_pk PRIMARY KEY (id)
);

CREATE TABLE Player (
    Id int  NOT NULL,
    Name varchar(30)  NOT NULL,
    Surname varchar(30)  NOT NULL,
    Team_Name varchar(20)  NOT NULL,
    CONSTRAINT Player_pk PRIMARY KEY (id)
);


ALTER TABLE Player ADD CONSTRAINT DZ
    FOREIGN KEY (Team_Name)
    REFERENCES Team (Team_Name)  
;


ALTER TABLE Game ADD CONSTRAINT MD
    FOREIGN KEY (Team1, Team2)
    REFERENCES Team (Team_Name, Team_Name)  
;


ALTER TABLE Mecz ADD CONSTRAINT MZ
    FOREIGN KEY (D1_Player1, D1_Player2, D1_Player3, D1_Player4, D1_zPlayer5, D1_Player6, D2_Player1, D2_Player2, D2_Player3, D2_Player4, D2_Player5, D2_Player6)
    REFERENCES Player (id, id, id, id, id, id, id, id, id, id, id, id)  
;

1 个答案:

答案 0 :(得分:0)

您应该逐个添加所有外键。

ALTER TABLE Game  ADD CONSTRAINT MZ
    FOREIGN KEY (D1_Player1)
    REFERENCES Player (id)  
;

ALTER TABLE Game  ADD CONSTRAINT MZ2
    FOREIGN KEY (D1_Player2)
    REFERENCES Player (id)  
;

ALTER TABLE Game  ADD CONSTRAINT MZ3
    FOREIGN KEY (D1_Player3)
    REFERENCES Player (id)  
;

GO

dbfiddle here