Reshad
Reshad

Reputation: 2652

cannot add foreign key in mysql

Hello I want to create a foreign key to relate 2 tables but when I am using this query

ALTER TABLE Player
ADD CONSTRAINT FK_team_id FOREIGN KEY (team_id)
REFERENCES Team(id);

I get the error Error code: 1215 Cannot add foreign key constraint

I am using a innoDB engine with utf8 encoding.. the tables Player and Team look like this

Player id PK Auto_increment etc .. .. team_id ( must be foreign key )

Team id PK ..

Anyone got the solution for this?

Here is the create table syntax

    CREATE TABLE `Player` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `Name` varchar(100) DEFAULT NULL,
  `Firstname` varchar(100) DEFAULT NULL,
  `Prefix` varchar(50) DEFAULT NULL,
  `Age` date DEFAULT NULL,
  `Position` varchar(2) DEFAULT NULL,
  `Caps` tinyint(3) DEFAULT NULL,
  `Goals` tinyint(3) DEFAULT NULL,
  `Captain` tinyint(1) DEFAULT NULL,
  `team_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

 CREATE TABLE `Team` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `Name` varchar(100) DEFAULT NULL,
  `Coach` varchar(100) DEFAULT NULL,
  `Prefix` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

Upvotes: 1

Views: 201

Answers (2)

ChrisLively
ChrisLively

Reputation: 88064

There are two main reasons why the contraint couldn't be added.

The first (and most likely) is that there is one or more team_id's data in the Player table that does not exist in the Team table.

The second is if the data types of the two tables are different.

Run the following query to see if there is a problem with the team id's in the player table:

select team_id
from Player
where team_id not in (select id from team)

Essentially that will identify team_ids that are missing. Fix as necessary. One thing to look for is a team_id in the player table of -1 or 0 (whatever your default is) which is not represented in the team table.

Upvotes: 0

Kermit
Kermit

Reputation: 34055

Make sure that the two columns are identical (SIGNED, NULLable, etc.). Also, any values that are being referenced must exist in the referenced table. Otherwise, run SHOW INNODB STATUS after attempting to create the key for further information.

Upvotes: 2

Related Questions