2014-05-23 108 views
0

我試圖插入到我的表中。球隊插入正確,但然後我想插入他們的隊顏色。但是,在此INSERT INTO下,只添加第一種顏色。然後我得到第二個錯誤。我如何告訴MySQL爲第二個團隊添加顏色等等?基本插入表mysql mysql

有更多的代碼,SQL,但是我想盡量簡短

CREATE TABLE team 
(
    team_id int NOT NULL AUTO_INCREMENT, 
    team varchar(255) NOT NULL, 
    conference varchar(255) NOT NULL, 
    division varchar(255) NOT NULL, 
    CONSTRAINT teamer FOREIGN KEY (team_id) REFERENCES player (team), 
    PRIMARY KEY (team) 
); 

CREATE TABLE color 
(
    team varchar(255) NOT NULL, 
    primary_color varchar(255) NOT NULL, 
    secondary_color varchar(255) NOT NULL, 
    CONSTRAINT colorer FOREIGN KEY (team) REFERENCES team (team), 
    PRIMARY KEY (team) 
); 


-- INSERT 
-- team 
INSERT INTO team (team, conference, division) 
VALUES ('SEA', 'NFC', 'N_WEST'); 

INSERT INTO team (team, conference, division) 
VALUES ('ARI', 'NFC', 'N_WEST'); 

INSERT INTO team (team, conference, division) 
VALUES ('SFO', 'NFC', 'N_WEST'); 

INSERT INTO team (team, conference, division) 
VALUES ('STL', 'NFC', 'N_WEST'); 


-- INSERT 
-- color 
INSERT INTO color (primary_color, secondary_color) 
VALUES ('Navy', 'Grey'); 

INSERT INTO color (primary_color, secondary_color) 
VALUES ('Red', 'White'); 

INSERT INTO color (primary_color, secondary_color) 
VALUES ('Red', 'Gold'); 

INSERT INTO color (primary_color, secondary_color) 
VALUES ('Navy', 'Gold'); 
+1

你什麼錯誤? – Barmar

+0

「SQL查詢: INSERT INTO顏色(primary_color,secondary_color) VALUES( '紅色', '白色' ); MySQL說:文檔 #1062 - 重複條目''的關鍵'PRIMARY'' – user3670475

+0

看到我的答案,我已經明白了。 – Barmar

回答

1

color表您指定team是主鍵。這意味着每行都必須有所不同。但是你沒有在你的INSERT聲明中指定團隊,所以它使用默認值,即空字符串。這會導致所有插入嘗試使用同一個團隊。由於團隊必須是唯一的,因爲嘗試創建副本,所以會出現錯誤。

你需要指定一個有效的隊名中插入顏色時:

INSERT INTO colors (team, primary_color, secondary_color) 
VALUES ('SEA', 'Navy', 'Grey'); 

INSERT INTO color (team, primary_color, secondary_color) 
VALUES ('ARI', 'Red', 'White');