外键和innodb引擎插入

时间:2016-02-11 12:17:01

标签: mysql

我无法在此表中插入薪水值 错误按摩Field'Tid'没有默认值

我通过添加约束或默认fk尝试了很多次但是它没有用到

我的代码就是这个

CREATE TABLE  Actor (
aid INTEGER NOT NULL AUTO_INCREMENT,
NAME VARCHAR(20),
PRIMARY KEY (aid)
) ENGINE=INNODB;

CREATE TABLE Movie (
mid INTEGER NOT NULL AUTO_INCREMENT,
NAME VARCHAR(30),
YEAR INTEGER,
PRIMARY KEY (mid)
) ENGINE=INNODB;

CREATE TABLE acts_in (
aid INTEGER  NOT  NULL AUTO_INCREMENT,
mid INTEGER NOT  NULL,
PRIMARY KEY (aid, mid),
FOREIGN KEY (aid) REFERENCES Actor (aid),
FOREIGN KEY (mid) REFERENCES Movie (mid) 
) ENGINE=INNODB;


SHOW TABLES;

INSERT INTO Actor(NAME)
VALUES ('Brad Pitt'), ('Edward Norton'), ('Julia Roberts');

INSERT INTO Movie (NAME, YEAR)
   VALUES ('Fight Club', 1999), ('Ocean\s Eleven', 2001), ('Fury', 2014), ('The Incredible Hulk', 2008), ('Closer', 2004);


INSERT INTO acts_in (aid, mid)
VALUES (1, 1), (1, 2), (1, 3),(2, 1), (2, 4), (3,2), (3, 5);

ALTER TABLE Acts_in 
ADD COLUMN Salary INTEGER NOT NULL;

INSERT INTO acts_in (Salary)
VALUES (2000), (4000), (5000), (50), (7000), (750000), (888888);

1 个答案:

答案 0 :(得分:0)

您的 acts_in 表是子表。 acts_in 表的父表是:

  1. 演员
  2. 电影
  3. 因此,如果父表中不存在相应的外键值,则无法添加或更新子表行。

    在这种情况下,您无法执行此查询:

    INSERT INTO acts_in (Salary)
    VALUES (2000), (4000), (5000), (50), (7000), (750000), (888888);
    

    您正在尝试添加或更新子表,但未设置aidmid的任何值。

    请尝试使用以下查询来更新工资:

    UPDATE acts_in SET Salary = 2000 WHERE aid = 1 AND mid = 1;
    UPDATE acts_in SET Salary = 4000 WHERE aid = 1 AND mid = 2;
    UPDATE acts_in SET Salary = 5000 WHERE aid = 1 AND mid = 3;
    UPDATE acts_in SET Salary = 50 WHERE aid = 2 AND mid = 1;
    UPDATE acts_in SET Salary = 7000 WHERE aid = 2 AND mid = 4;
    UPDATE acts_in SET Salary = 750000 WHERE aid = 3 AND mid = 2;
    UPDATE acts_in SET Salary = 888888 WHERE aid = 3 AND mid = 5;
    

    这个单一查询:

    UPDATE 
    acts_in
    SET Salary = CASE WHEN aid = 1 AND mid = 1 THEN 2000
                      WHEN aid = 1 AND mid = 2 THEN 4000
                      WHEN aid = 1 AND mid = 3 THEN 5000
                      WHEN aid = 2 AND mid = 1 THEN 50
                      WHEN aid = 2 AND mid = 4 THEN 7000
                      WHEN aid = 3 AND mid = 2 THEN 750000
                      WHEN aid = 3 AND mid = 5 THEN 888888 
                  END
    WHERE (aid,mid) IN ((1,1),(1,2),(1,3),(2,1),(2,4),(3,2),(3,5));
    

    注意:在这种情况下,您尝试更新子表,其中相应的外键(在本例中为aidmid)包含有效值。 / p>

    选中SQL FIDDLE