更正多个外键的外键约束的语法

时间:2015-05-20 15:17:05

标签: sql sql-server sql-server-2005 foreign-keys foreign-key-relationship

根据此示例,对于多个外键的foreign key constraint,所有引用来自引用表的相同primary key的正确语法是什么?

ALTER TABLE team
ADD CONSTRAINT fk_team_players
FOREIGN KEY (player_1, player_2, player_3, player_4, player_5, player_6, player_7, player_8) 
REFERENCES player (player_id)

1 个答案:

答案 0 :(得分:5)

你必须分开进行:

ALTER TABLE team
ADD CONSTRAINT fk_team_players1
FOREIGN KEY (player_1) 
REFERENCES player (player_id)

ALTER TABLE team
ADD CONSTRAINT fk_team_players2
FOREIGN KEY (player_2) 
REFERENCES player (player_id)

...
ALTER TABLE team
ADD CONSTRAINT fk_team_players8
FOREIGN KEY (player_8) 
REFERENCES player (player_id)

您也可以按照以下一条指令进行操作

ALTER TABLE team
ADD CONSTRAINT fk_team_players1 FOREIGN KEY (player_1) REFERENCES player (player_id),
ADD CONSTRAINT fk_team_players2 FOREIGN KEY (player_2) REFERENCES player (player_id),
...  
ADD CONSTRAINT fk_team_players8 FOREIGN KEY (player_8) REFERENCES player (player_id),

我建议您更改表格结构,以使玩家不在列中但在行中的其他表格中。