外键约束

-- 成绩表
-- 添加外键的语法格式:
-- CONSTRAINT 外键名称 FOREIGN KEY (外键字段) REFERENCES 表名(主键)
CREATE TABLE score(
    id int PRIMARY KEY AUTO_INCREMENT,
  score int,
  name varchar(10) NOT NULL,
  sid  int,
    CONSTRAINT fk_student_score FOREIGN KEY(sid) REFERENCES student(id)
);

INSERT INTO score (score,name,sid) VALUES (90,'数学',1);
INSERT INTO score (score,name,sid) VALUES (93,'数学',2);

-- 插入会报错  [Err] 1452 - Cannot add or upda
-- te a child row: a foreign key constraint fails (`gjp`.`score`, 
-- CONSTRAINT `fk_student_score` FOREIGN KEY (`sid`) REFERENCES `student` (`id`))
INSERT INTO score (score,name,sid) VALUES (98,'数学',3); 

 

 

posted @ 2018-12-23 17:07  expworld  阅读(109)  评论(0)    收藏  举报