The correct foreign key constraint syntax for multiple foreign keys

According to this example, what is the correct syntax for foreign key constraintfor multiple foreign keys that reference the same primary keyreference table?

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)
+4
source share
1 answer

You must do this separately:

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)

You can also do this in one instruction, as shown below.

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),

I recommend that you change the structure of the table so that players are not in columns, but in another table in rows.

+5
source

Source: https://habr.com/ru/post/1589038/


All Articles