2016-04-26 19 views
1

私はチュートリアルで私の練習課題にMySQLを使用していますが、エラー "誤った制約"を持つテーブルを作成する際に問題があります。MySQL - errno 150: "外部キー制約が正しく形成されていません"

私はそれを修正する方法を見て、私に提案してください。ありがとうございました!もちろん祭が講師はもちろん、製品に割り当てられている学生はもちろん、提供、ないコース *に入学します*特定の学期 で提供されるコースがある*

、ないコース

あなたが必要
CREATE TABLE `students` (
    `student_id` char(8) NOT NULL, 
    `max_load` tinyint(4) NOT NULL, 
    PRIMARY KEY (`student_id`) 
) 
CREATE TABLE `courses` (
`course_code` char(8) NOT NULL, 
`course_title` varchar(100) NOT NULL, 
PRIMARY KEY (`course_code`) 
) 
CREATE TABLE `lecturers` (
    `lecturer_id` char(8) NOT NULL, 
    `lecturer_name` varchar(50) NOT NULL, 
    PRIMARY KEY (`lecturer_id`) 
) 

CREATE TABLE `course_offerings` (
    `course_code` char(8) NOT NULL, 
    `semester` tinyint(4) NOT NULL, 
    `year` year(4) NOT NULL, 
    `lecturer_id` char(8) NOT NULL, 
    PRIMARY KEY (`course_code`,`semester`,`year`), 
    FOREIGN KEY (`course_code`) REFERENCES `courses` (`course_code`), 
    FOREIGN KEY (`lecturer_id`) REFERENCES `lecturers` (`lecturer_id`) 
) 

CREATE TABLE `enrolment` (
`student_id` char(8) NOT NULL, 
`course_code` char(8) NOT NULL, 
`semester` tinyint(4) NOT NULL, 
`year` year(4) NOT NULL, 
PRIMARY KEY (`student_id`,`course_code`,`semester`,`year`), 
FOREIGN KEY (`student_id`) REFERENCES students(`student_id`), 
FOREIGN KEY (`course_code`) REFERENCES course_offerings(`course_code`), 
FOREIGN KEY (`semester`) REFERENCES course_offerings(`semester`), 
FOREIGN KEY (`year`) REFERENCES course_offerings(`year`) 
) 

答えて

1

複合外部キーをenrolmentに設定しようとしていますか?それが事実なら、あなたが望むものは次のようなものかもしれません。

CREATE TABLE `enrolment` (
    `student_id` char(8) NOT NULL, 
    `course_code` char(8) NOT NULL, 
    `semester` tinyint(4) NOT NULL, 
    `year` year(4) NOT NULL, 
PRIMARY KEY (`student_id`,`course_code`,`semester`,`year`), 
FOREIGN KEY (`student_id`) 
    REFERENCES students(`student_id`), 
FOREIGN KEY (`course_code`, `semester`, `year`) 
    REFERENCES course_offerings(`course_code`, `semester`, `year`)) 

私はcourse_code、学期と年がUNIQUEキーを組み合わせ維持、course_offeringsでid列を作成し、その主キーを作るためにあなたをお勧めしたいです。このidを外部キーとして使用すると、3列の代わりに1列が必要になります。

+1

ありがとう、私はあなたの提案に従います。 –

0

送信元と送信先テーブルの間で、NOT NULL semester tinyint型、 year年、NOT NULL、 対のコラムのあなたのタイプをチェックし semester tinyint型(4)NOT NULL、 year年(4)NOT NUL L、

+0

それは私がすべてのことを確認した後も助けdoes notの。それでも、長さ(4)、年(8)、およびtinyint ...は、このようなタイプのデフォルトの長さであるため、ウィザードによって自動的に追加されます。 –

-1

これはどうですか?

ALTER TABLE `kategori_transportasi` ADD FOREIGN KEY (`no_ktp_pemesan`) REFERENCES `tbl_daftar_customer` (
`no_ktp_pemesan`); 

MySQLは言った:ドキュメント

#1005 - Can't create table `kuda_express`.`#sql-d64_216` (errno: 150 "Foreign key constraint is incorrectly formed") (Details…) 
関連する問題