2017-03-09 70 views
-1

這是我的代碼:爲什麼我不能添加外鍵約束

CREATE DATABASE exams; 

SHOW DATABASES; 

CREATE TABLE IF NOT EXISTS students(
    student_id INT UNSIGNED NOT NULL AUTO_INCREMENT, 
    first_name VARCHAR(20) NOT NULL, 
    middle_name VARCHAR(40), 
    last_name VARCHAR(40)NOT NULL, 
    email VARCHAR(60) NOT NULL, 
    password CHAR(40) NOT NULL, 
    reg_date DATETIME NOT NULL, 
    PRIMARY KEY (student_id), 
    UNIQUE(email)); 

SHOW table status 
INSERT INTO exams_3121(student_id, first_name, middle_name, last_name, email, password, reg_date) 

CREATE TABLE entries 
(
entrie_id int NOT NULL, 
student_id int NOT NULL, 
subject_id int, 
PRIMARY KEY (entrie_id), 
FOREIGN KEY (student_id) REFERENCES student(student_id), 
FOREIGN KEY (subject_id)REFERENCES subject(subject_id) 
) 
CREATE DATABASE subjects; 

CREATE TABLE IF NOT EXISTS subjects(
subject_id INT UNSIGNED NOT NULL AUTO_INCREMENT, 
subject_name VARCHAR(20) NOT NULL, 
level_entery VARCHAR(40)NOT NULL, 
exam_board VARCHAR(60) NOT NULL, 
PRIMARY KEY (subject_id)); 

CREATE TABLE entries 
(
entrie_id int NOT NULL, 
entrie_id int NOT NULL, 
subject_id int, 
PRIMARY KEY (entrie_id), 
FOREIGN KEY (student_id) REFERENCES student(student_id), 
FOREIGN KEY (subject_id)REFERENCES subject(subject_id) 
) 

當我使用此代碼,它說不能添加外鍵約束 ,我不知道該怎麼辦。請提前致謝。

+0

表中沒有'student_id'列。你有兩次'entrie_id'。 – Barmar

+0

不幸的是,當涉及到外鍵定義錯誤時,MySQL隱藏了實際的錯誤信息。您需要運行'SHOW ENGINE INNODB STATUS'並在* LATEST FOREIGN KEY ERROR *部分找到它。請注意[顯示引擎查詢](https://dev.mysql.com/doc/refman/5.7/en/show-engine.html)需要['PROCESS'特權](https://dev.mysql。 com/doc/refman/5.7/en/privileges-provided.html#priv_process),您的普通MySQL用戶可能沒有 - 您可以分配權限或以root身份運行查詢。 –

+0

@Barmar我有一個'student_id'列,除了它在另一個表中。 –

回答

0

有兩個問題。

首先,您得到了您引用的表的名稱錯誤。表的名稱是studentssubjects,但是您寫了studentsubject

二,entries表有兩個entrie_id列。其中一個應該是student_id

CREATE TABLE entries 
(
    entrie_id int NOT NULL, 
    student_id int NOT NULL, 
    subject_id int, 
    PRIMARY KEY (entrie_id), 
    FOREIGN KEY (student_id) REFERENCES students(student_id), 
    FOREIGN KEY (subject_id) REFERENCES subjects(subject_id) 
) 

另外,如果您正在創建多個數據庫,並把你的表在其中,你需要,如果他們從你與USE默認選擇一個不同的指表與他們的數據庫前綴命令。正如你寫的那樣,你實際上並沒有使用CREATE DATABASE創建的數據庫。