Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct syntax for foreign key constraint for multiple foreign keys

As per this example what is the correct syntax for a foreign key constraint for multiple foreign keys that all reference the same primary key from the referenced 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)
like image 918
stonypaul Avatar asked May 20 '15 15:05

stonypaul


People also ask

What is the correct foreign key constraint?

A foreign key joins a table to another table by referencing its primary key. A foreign key constraint specifies that the key can only contain values that are in the referenced primary key, and thus ensures the referential integrity of data that is joined on the two keys.

Can we have multiple foreign keys in a table?

A single column can have multiple foreign key constraints. For an example, see Add multiple foreign key constraints to a single column.

Can I have 3 foreign keys?

A table with a foreign key reference to itself is still limited to 253 foreign key references. Greater than 253 foreign key references are not currently available for columnstore indexes, memory-optimized tables, Stretch Database, or partitioned foreign key tables.


1 Answers

You have to do them 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 it in one instruction as 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 you to change table structure to keep players not in columns but in other table in rows.

like image 199
Robert Avatar answered Oct 16 '22 07:10

Robert