我试图添加这些数据。但是,它不允许我。如何添加与学生相关的成绩?
出现的错误代码是“
错误代码:1452。无法添加或更新子行:外键约束失败(university
。grade_report
,CONSTRAINT grade_report_ibfk_1
FOREIGN KEY(Student_number
)参考STUDENT
(Student_number
))
可能的解决方案?
Create database UNIVERSITY;
USE UNIVERSITY;
CREATE TABLE STUDENT(
Name VARCHAR(150),
Student_number INT,
Class INT,
Major VARCHAR(50),
PRIMARY KEY (Student_number)
);
CREATE TABLE UNIT (
Unit_name VARCHAR(120),
Unit_number VARCHAR(20),
Credit INT,
School VARCHAR(10),
PRIMARY KEY (Unit_number)
);
CREATE TABLE SECTION (
Section_id INT,
Unit_number VARCHAR(20),
Semester INT,
Year INT,
Lecturer VARCHAR(150),
PRIMARY KEY (Section_id),
FOREIGN KEY (Unit_number) REFERENCES UNIT(Unit_number)
);
CREATE TABLE GRADE_REPORT (
Student_number INT,
Section_id INT,
Grade INT,
FOREIGN KEY (Student_number) REFERENCES STUDENT(Student_number),
FOREIGN KEY (Section_id) REFERENCES SECTION (Section_id)
);
INSERT INTO STUDENT
VALUES
('Smith', 17, 1, 'CS'),
('Brown', 8, 2, 'CS’);
INSERT INTO UNIT
VALUES
(‘Intro to CS’, ‘IN101’, 8, ‘CS’),
(‘Data Structures’, ‘CS302’, 8, ‘CS’),
(‘Database’, ‘IAB130’, 8, ‘IS’),
(‘Discrete Maths’, ‘MATH120’, 10, ‘MATH’);
INSERT INTO SECTION
VALUES
(85, ‘IN101’, 1, 2012, ‘Smith’),
(102, ‘CS302’, 1, 2012, ‘King’),
(103, ‘IN101’, 2, 2013, ‘Baily’),
(96, ‘MATH120’, 1, 2012, ‘Jones’);
问题出在这里:
INSERT INTO GRADE_REPORT
VALUES
(17, 85, 7),
(8, 103, 5),
(8, 102, 6),
(8, 85, 6),
(9, 85, 5),
(17, 96, 4);
答案 0 :(得分:1)
U必须为每个数据目的地定义字段,如此
INSERT INTO GRADE_REPORT (`Student_number`,`Section_id`,`Grade`) VALUES (17, 85, 7), (8, 103, 5), (8, 102, 6), (8, 85, 6), (9, 85, 5), (17, 96, 4);