2017-09-22 62 views
0

我正在嘗試創建一組玩家和團隊。每個玩家都屬於一個團隊。我在team表中引用'team'屬性爲屬性'teamID'。不過,我不斷收到錯誤:「請檢查表上的球員外鍵約束的父表隊」SQL中的外鍵引用不起作用

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; 
+0

Mysql或postgresql? –

回答

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); 
1

在引用錶行必須存在可以插入一排之前。您正嘗試將行插入players。但是這些都是參考團隊。

您需要先插入teams記錄。