在MySQL中更改表时出现错误

时间:2019-10-01 09:53:36

标签: mysql sql

我写了一个sql文件来创建Database,并在其中tables中添加database
这是代码:

CREATE SCHEMA `employee_details`;
CREATE TABLE `employee_details`.`employee` (
    `emp_id` INT NOT NULL AUTO_INCREMENT,
    `name` VARCHAR(45),
    `dob` DATE,
    `joiningdate` DATE,
    `designation_id` INT,
    `gender` VARCHAR(45),
    `address` VARCHAR(90),
    `manager_id` INT,
    PRIMARY KEY (`emp_id`)
);

CREATE TABLE `employee_details`.`designation` (
    `designation_id` INT NOT NULL AUTO_INCREMENT,
    `designation` VARCHAR(45),
    `dept_id` INT,
    `salary` FLOAT,
    PRIMARY KEY (`designation_id`)
);

CREATE TABLE `employee_details`.`department` (
    `dept_id` integer NOT NULL AUTO_INCREMENT,
    `dept_name` VARCHAR(45),
    PRIMARY KEY (`dept_id`)
);

CREATE TABLE `employee_details`.`rating` (
    `emp_id` INT,
    `emp_rating` INT,
    `add_perks` FLOAT,
    `experience` INT
);

CREATE TABLE `employee_details`.`project_assign` (
    `emp_id` INT,
    `project_id` INT
);

CREATE TABLE `employee_details`.`project` (
    `project_id` INT NOT NULL AUTO_INCREMENT,
    `project_name` VARCHAR(45),
    `project_dept` INT,
    PRIMARY KEY (`project_id`)
);

ALTER TABLE employee 
ADD FOREIGN KEY (emp_id) REFERENCES rating(emp_id);

ALTER TABLE employee 
ADD FOREIGN KEY (emp_id) REFERENCES project_assign(emp_id);

ALTER TABLE employee 
ADD FOREIGN KEY (emp_id) REFERENCES employee(manager_id);

ALTER TABLE designation 
ADD FOREIGN KEY (designation_id) REFERENCES employee(designation_id);

ALTER TABLE designation 
ADD FOREIGN KEY (dept_id) REFERENCES department(dept_id);

ALTER TABLE department 
ADD FOREIGN KEY (dept_id) REFERENCES project(project_dept);

ALTER TABLE project 
ADD FOREIGN KEY (project_id) REFERENCES project_assign(project_id);

执行该sql文件时,出现以下错误:

  

15:16:50更改表员工添加外键(emp_id)参考等级(emp_id)错误代码:1822。无法添加外键约束。引用表“评级” 0.000秒中缺少约束“ employee_ibfk_1”的索引

我检查了emp_idemployeerating的数据类型。他们是一样的。如何解决此错误?

1 个答案:

答案 0 :(得分:2)

您所有的外键关系都是向后的。应该是:

ALTER TABLE rating
ADD FOREIGN KEY (emp_id) REFERENCES employee(emp_id);

,其他所有外键都类似。