简体   繁体   中英

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;

Make sure that the two columns are identical ( SIGNED , NULL able, 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM