MYSQL 中键和表引用错误 - 引用错误

问题描述 投票:0回答:1

这是我的 SQL 查询

CREATE TABLE Course (
    Cname VARCHAR(255),
    Department VARCHAR(255),
    PRIMARY KEY (Cname, Department)
); 

CREATE TABLE Student (
    student_id VARCHAR(255) PRIMARY KEY,
    first_name VARCHAR(255),
    last_name VARCHAR(255),
    student_email VARCHAR(255),
    student_password VARCHAR(255),
    enrollment_number INT,
    current_year INT,
    branch VARCHAR(255),
    course VARCHAR(255),
    profile_photo BLOB,
    FOREIGN KEY (course) REFERENCES Course(Cname, Department)
);

这是错误:

错误代码:1239。“外键”的外键定义不正确 没有名称':关键参考和表格参考不匹配

这是插入内容(如果有帮助的话):

INSERT INTO Course (Cname, Department) VALUES
('MCA', 'NA'),
('BTECH', 'CSE'),
('BTECH', 'CIVIL'),
('BTECH', 'MECHANICAL'),
('BTECH', 'ELECTRICAL');


INSERT INTO Student (student_id, first_name, last_name, student_email, student_password, enrollment_number, current_year, branch, course, profile_photo) 
VALUES
(2320403214, 'Vivek', 'Ojha', '[email protected]', '123', 2023, 1, 'MCA', 'NA', 'photo.png');
mysql foreign-keys
1个回答
0
投票

您的

Course
表有两个“主键”,列
CName
是重复的,如下所示:

您想如何使用

Course
表中的
Student
数据?想想吧🤔。

为什么不在

CID
表中引入
Course
列,并将该列用作
FOREIGN KEY
表中的
Student

根据数据,

Student
表中的列的目的是什么?

根据数据,我认为

branch, course
Cname, Department
对于
Course
表。

无论如何,我在

PRIMARY KEY
表中引入单个
Course
后解决了这个问题。

drop table if exists student;
drop table if exists Course;
-- ====================
CREATE TABLE Course (
    cid VARCHAR(255) NOT NULL,
    Cname VARCHAR(255),
    Department VARCHAR(255),
    PRIMARY KEY (cid)
) ENGINE=INNODB;
desc course;
INSERT INTO Course (cid, Cname, Department) VALUES
('01', 'MCA', 'NA'),
('02', 'BTECH', 'CSE'),
('03', 'BTECH', 'CIVIL'),
('04', 'BTECH', 'MECHANICAL'),
('05', 'BTECH', 'ELECTRICAL');
select * from Course;
-- ====================
CREATE TABLE Student (
    student_id VARCHAR(255) NOT NULL PRIMARY KEY,
    first_name VARCHAR(255),
    last_name VARCHAR(255),
    student_email VARCHAR(255),
    student_password VARCHAR(255),
    enrollment_number INT,
    current_year INT,
    branch VARCHAR(255),
    course VARCHAR(255),
    profile_photo BLOB,
    FOREIGN KEY (course)
        REFERENCES Course(cid)
        ON DELETE CASCADE
) ENGINE=INNODB;
desc student;
INSERT INTO Student (student_id, first_name, last_name, student_email, student_password, enrollment_number, current_year, branch, course, profile_photo) 
    VALUES ('2320403214', 'Vivek', 'Ojha', '[email protected]', 'pass123', 2023, 1, 'MCA', NULL, 'photo.png');
INSERT INTO Student
    VALUES ('2320403215', 'Jiban', 'Ojha', '[email protected]',       'pass345', 2022, 2, 'MCA', '01', 'photo1.png');
select * from student;

结果:

💡请使用MySQL参考:💡

https://dev.mysql.com/doc/refman/8.0/en/create-table-foreign-keys.html

© www.soinside.com 2019 - 2024. All rights reserved.