我想将所有这些表(学生,老师,课程)链接到父表(班级),但是我有错误?

时间:2019-11-22 16:48:52

标签: mysql sql database

 CREATE TABLE student 
 (
 s_id INTEGER  ,
 s_name VARCHAR2(80) ,
 s_email VARCHAR (80) ,
 FOREIGN KEY (s_id) REFERENCES classes (s_id)
 );
 CREATE TABLE teacher 
 (
 t_id INTEGER ,
 t_name VARCHAR2(80) ,
 t_email VARCHAR2 (80) ,
 FOREIGN KEY (t_id) REFERENCES classes (t_id)
 );
 CREATE TABLE courses
 (
 c_id INTEGER  ,
 c_title VARCHAR2 (25) ,
 c_describetion VARCHAR2 (25) ,
 FOREIGN KEY (c_id) REFERENCES classes (c_id)
 );
 CREATE TABLE classes
 (
 cl_name VARCHAR2 (30) ,
 cl_number INTEGER ,
 t_id INTEGER ,
 s_id INTEGER ,
 c_id INTEGER ,
 PRIMARY KEY (cl_number , t_id , s_id , c_id)
 );
  • 当我需要创建这些表(学生,老师,课程)时,出现此错误:
    错误报告 - ORA-02270:此列列表没有匹配的唯一键或主键
    1. 00000-“此列列表没有匹配的唯一键或主键” *原因:CREATE / ALTER TABLE语句中的REFERENCES子句    给出没有匹配的唯一或主要的列列表    引用表中的键约束。 *操作:使用ALL_CONS_COLUMNS查找正确的列名称    目录视图

2 个答案:

答案 0 :(得分:1)

您要从其他三个表中引用表“类”。这是应该引用这些的类。将FK放在引用相应表的“ id”字段的类的列中。另外,我认为您需要将它们定义为PK / UNIQUE。

答案 1 :(得分:1)

您正在以相反的方式创建外键。您希望classes具有引用其他表的外键。您还需要在3个主表中定义主键,以便可以将它们称为外键。

此外,MySQL中没有VARCHAR2数据类型(这是Oracle特定的数据类型):请改用VARCHAR。

考虑:

CREATE TABLE student (
    s_id INTEGER PRIMARY KEY,
    s_name VARCHAR(80),
    s_email VARCHAR(80)
);

CREATE TABLE teacher (
    t_id INTEGER PRIMARY KEY,
    t_name VARCHAR(80),
    t_email VARCHAR(80) 
);

CREATE TABLE courses (
     c_id INTEGER PRIMARY KEY,
     c_title VARCHAR(25),
     c_description VARCHAR(25) 
);

 CREATE TABLE classes (
     cl_name VARCHAR(30),
     cl_number INTEGER,
     t_id INTEGER,
     s_id INTEGER,
     c_id INTEGER,
     PRIMARY KEY (cl_number , t_id , s_id , c_id),
     FOREIGN KEY (s_id) REFERENCES student (s_id),
     FOREIGN KEY (t_id) REFERENCES teacher (t_id),
     FOREIGN KEY (c_id) REFERENCES courses (c_id)
);

Demo on DB Fiddle


如果您运行的是Oracle(如问题中的错误消息所示)而不是MySQL(为您的问题加了标签),那么您想要的是VARCHAR2而不是VARCHAR(已弃用) 。脚本的其余部分保持不变:

CREATE TABLE student (
    s_id INTEGER PRIMARY KEY,
    s_name VARCHAR2(80),
    s_email VARCHAR2(80)
);

CREATE TABLE teacher (
    t_id INTEGER PRIMARY KEY,
    t_name VARCHAR2(80),
    t_email VARCHAR2(80) 
);

CREATE TABLE courses (
     c_id INTEGER PRIMARY KEY,
     c_title VARCHAR2(25),
     c_description VARCHAR2(25) 
);

 CREATE TABLE classes (
     cl_name VARCHAR2(30),
     cl_number INTEGER,
     t_id INTEGER,
     s_id INTEGER,
     c_id INTEGER,
     PRIMARY KEY (cl_number , t_id , s_id , c_id),
     FOREIGN KEY (s_id) REFERENCES student (s_id),
     FOREIGN KEY (t_id) REFERENCES teacher (t_id),
     FOREIGN KEY (c_id) REFERENCES courses (c_id)
);

Demo on DB Fiddle