MySql外键不正确

时间:2017-01-14 16:55:22

标签: mysql database foreign-keys localhost primary-key

我正在使用xampp(localhost)和mysql为项目创建一个数据库,但我有外键问题,当我试图创建学生注册表时,我无法找到我的错误这是我得到的消息: #1005 - 无法创建表Xstudentenrolment(错误:150"外键约束形成错误")

我的表格代码:

CREATE TABLE LOGINFO (
STUDENTNUMBER   NUMERIC(9) NOT NULL,
PASS CHAR(12),
CONSTRAINT LOGINFO_PRIMARY_KEY PRIMARY KEY (STUDENTNUMBER));

CREATE TABLE LEADERS(
MODULESLEADER CHAR(16) NOT NULL,
LEADERSOFFICE CHAR(16) ,
LEADERSEMAIL  CHAR(16) ,
LEADERSPHONE numeric(4),
CONSTRAINT LEADERS_PRIMARY_KEY PRIMARY KEY (MODULESLEADER));

CREATE TABLE MODULES(
MODULESLEADER CHAR(16) NOT NULL,
MODULECODE CHAR(6) NOT NULL ,
MODULEDESCRIPTION CHAR(16) ,
LECTURESLOT CHAR (16),
LECTUREROOM CHAR(4) ,
CONSTRAINT MODULES_FOREIGN_KEY FOREIGN KEY (MODULESLEADER) REFERENCES LEADERS (MODULESLEADER),
CONSTRAINT MODULES_PRIMARY_KEY PRIMARY KEY (MODULESLEADER,MODULECODE));

CREATE TABLE STUDENTENROLMENT(
STUDENTNUMBER NUMERIC(9) NOT NULL,
MODULECODE CHAR(6) NOT NULL ,
CONSTRAINT STUDENTENROLMENT_FOREIGN_KEY FOREIGN KEY (STUDENTNUMBER) REFERENCES LEADERS (STUDENTNUMBER), 
CONSTRAINT STUDENTENROLMENT_FOREIGN_KEY FOREIGN KEY (MODULECODE) REFERENCES MODULES (MODULECODE), 
CONSTRAINT STUDENTENROLMENT_PRIMARY_KEY PRIMARY KEY (STUDENTNUMBER, MODULECODE));   

我正在努力寻找我的语法错误但我无法找到它我尝试了许多其他方式:

CONSTRAINT STUDENTENROLMENT2_FOREIGN_KEY FOREIGN KEY (MODULECODE) REFERENCES MODULES (MODULECODE)

提前谢谢你!

1 个答案:

答案 0 :(得分:0)

  1. 我认为FOREIGN KEY(STUDENTNUMBER)应该指定LOGINFO表。
  2. 也许this question可以提供帮助
  3. 似乎此代码不会导致错误:

    CREATE TABLE LOGINFO (
      STUDENTNUMBER   NUMERIC(9) NOT NULL,
      PASS CHAR(12),
      CONSTRAINT LOGINFO_PRIMARY_KEY PRIMARY KEY (STUDENTNUMBER));
    
    CREATE TABLE LEADERS(
      MODULESLEADER CHAR(16) CHARACTER SET utf8 NOT NULL,
      LEADERSOFFICE CHAR(16) ,
      LEADERSEMAIL  CHAR(16) ,
      LEADERSPHONE numeric(4),
      CONSTRAINT LEADERS_PRIMARY_KEY PRIMARY KEY (MODULESLEADER));
    
    CREATE TABLE MODULES(
      MODULESLEADER CHAR(16) CHARACTER SET utf8 NOT NULL,
      MODULECODE CHAR(6) CHARACTER SET utf8 NOT NULL ,
      MODULEDESCRIPTION CHAR(16) ,
      LECTURESLOT CHAR (16),
      LECTUREROOM CHAR(4) ,
      CONSTRAINT MODULES_FOREIGN_KEY FOREIGN KEY (MODULESLEADER) REFERENCES LEADERS (MODULESLEADER),
      CONSTRAINT MODULES_PRIMARY_KEY PRIMARY KEY (MODULECODE, MODULESLEADER));
    
    
    
    CREATE TABLE STUDENTENROLMENT
    (
      STUDENTNUMBER NUMERIC(9) NOT NULL,
      MODULECODE CHAR(6) CHARACTER SET utf8 NOT NULL,
      CONSTRAINT STUDENTENROLMENT_MODULES_MODULECODE_fk FOREIGN KEY (MODULECODE) REFERENCES MODULES (MODULECODE)
     ,CONSTRAINT STUDENTENROLMENT_LOGINFO_STUDENTNUMBER_fk FOREIGN KEY (STUDENTNUMBER) REFERENCES LOGINFO (STUDENTNUMBER),
      CONSTRAINT STUDENTENROLMENT_PRIMARY_KEY PRIMARY KEY (STUDENTNUMBER, MODULECODE)
    );