基本插入表mysql

时间:2014-05-23 22:09:59

标签: mysql

我试图插入我的桌子。团队正确插入,但我想插入他们的团队颜色。但是在此INSERT INTO下,只有第一种颜色添加。然后我得到第二个错误。如何告诉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 个答案:

答案 0 :(得分: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');