SQL错误1452:无法添加或更新子级

时间:2017-04-24 15:15:38

标签: mysql sql-server

Create table Course(CourseID char(5),CourseDesc varchar(25),CourseType char(9),SemNo int(1),FacID char(4) default 0);
alter table Course add primary key(CourseID);
alter table Course add foreign key(FacID) references Faculty1(FacID);

这里FacID是Faculty主键的外键 当我插入值时,我尝试插入此值

insert into Course(CouseID,CourseDesc,CourseType,SemNo,FacID) values ('EE025','Digital Logic Circuits','Theory','4','');

但是,这会产生sql错误1452,请解决它。

2 个答案:

答案 0 :(得分:0)

您在插入中拼错了CourseID:

    data:any;
    questions : QuestionBase<any>[] = [];

    getQuestions() Observable<QuestionsBase[]> {
        return this.http.get(this.questionUrl)
            .map(res => res.json())
            .map(data => {
                this.data = data;
                this.buildQuestions(data);
    )};

    buildQuestions(data){
        for (let key in data) {
            //push Objects in this.questions array
        }
        return this.questions.sort((a, b) => a.order - b.order);
    }

应该是:

insert into Course(CouseID,CourseDes...

答案 1 :(得分:0)

您是否确认Faculty1中有一行FacID = 0

insert into Faculty1 (FacID /* other columns */) values (0 /*, other values*/ );
insert into Course(CourseID,CourseDesc,CourseType,SemNo,FacID) values ('EE025','Digital Logic Circuits','Theory',4,0);

如果要插入空值(''),则需要在Faculty1.FacID中包含空字符串值。否则,您可以正确指出'0'

create table Faculty1(
    FacID char(4) not null primary key
);
insert into faculty1 values (0);

create table Course(
    CourseID char(5) not null
  , CourseDesc varchar(25)
  , CourseType char(9)
  , SemNo int
  , FacID char(4) not null default 0 
    /* specify not null to use default when value not inserted */
); 
alter table Course add primary key(CourseID);
alter table Course add foreign key(FacID) references Faculty1(FacID);

/* inserting `''` instead of `0` for FacId results in an error */
begin try;
insert into Course(CourseID,CourseDesc,CourseType,SemNo,FacID) values 
('EE025','Digital Logic Circuits','Theory','4','');
end try
begin catch
select error_message();
end catch;

/* inserting `0` for FacId = no error*/
insert into Course(CourseID,CourseDesc,CourseType,SemNo,FacID) values 
  ('EE025','Digital Logic Circuits','Theory',4,'0');
select * from Course;

/* inserting without specifying FacId uses default*/
insert into Course(CourseID,CourseDesc,CourseType,SemNo) values 
  ('EE026','Digital Logic Circuits','Theory',4);
select * from Course;

rextester演示:http://rextester.com/ZYGWRX20984