SQL中的外键引用不起作用

时间:2017-09-22 19:33:49

标签: mysql sql foreign-keys

我正在尝试创建一组球员和球队。每个球员都属于一个球队。我将一个'team'属性引用到teams表中的属性'teamID'。但我一直收到错误:“请检查父表组队员的桌面玩家的外键约束”

CREATE TABLE players (
  playerid    INTEGER PRIMARY KEY, 
  name  text,
  position text,
  skill text,
  team integer,
  FOREIGN KEY(team) REFERENCES teams(teamID)

);

CREATE TABLE teams (
  teamID     INTEGER primary key, 
  name   text unique, 
  city text,
  coach text
  /*captain text*/

);

INSERT INTO players VALUES (1, "Tom Chapin", "Quorter Back", "Advanced SKill", 1);
INSERT INTO players VALUES (2, "Harry Chapin", "LineBacker", "Begginer", 2);

/* Tom's songs */
INSERT INTO teams VALUES (1, "Chicago Bears", "Chicago", "Coach Jack");
INSERT INTO teams VALUES (2, "Detroit Bulls", "Detroit", "Coach Bob");
/* Harry's songs */
INSERT INTO teams VALUES (3, "NY Snakes", "New York", "Coach Phil");


SELECT * from players;
SELECT * FROM teams;

2 个答案:

答案 0 :(得分:1)

在可以插入行之前,引用表中的行需要存在

您正在尝试将行插入players。但这些都是引用团队的。

您需要先插入teams条记录。

答案 1 :(得分:0)

请在创建表格播放器之前创建表格团队。

CREATE TABLE teams (
  teamID     INTEGER primary key, 
  name   varchar(255) unique, 
  city text,
  coach text
)

CREATE TABLE players (
  playerid    INTEGER PRIMARY KEY, 
  name  varchar(255),
  position text,
  skill text,
  team integer,
  FOREIGN KEY(team) REFERENCES teams(teamID)

);


/* Tom's songs */
INSERT INTO teams VALUES (1, "Chicago Bears", "Chicago", "Coach Jack");
INSERT INTO teams VALUES (2, "Detroit Bulls", "Detroit", "Coach Bob");
/* Harry's songs */
INSERT INTO teams VALUES (3, "NY Snakes", "New York", "Coach Phil");

INSERT INTO players VALUES (1, "Tom Chapin", "Quorter Back", "Advanced SKill", 1);
INSERT INTO players VALUES (2, "Harry Chapin", "LineBacker", "Begginer", 2);