任何人都可以帮我解决此代码的错误吗?

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

我正在尝试使用此代码更新员工表

UPDATE employee
SET branch_id = 1 
WHERE emp_id = 100;

这是之前使用的代码,它很长,请耐心等待。

CREATE TABLE employee (
    emp_id INT PRIMARY KEY,
    first_name VARCHAR(40),
    last_name VARCHAR(40),
    birth_day DATE,
    sex VARCHAR(1),
    salary INT,
    super_id INT,
    branch_id INT
);

CREATE TABLE branch (
    branch_id INT PRIMARY KEY,
    branch_name VARCHAR(40),
    mgr_id INT,
    mgr_start_date DATE,
    FOREIGN KEY (mgr_id) REFERENCES employee (emp_id) ON DELETE SET NULL
);

ALTER TABLE employee
ADD FOREIGN KEY (branch_id)
REFERENCES employee(emp_id)
ON DELETE SET NULL;

ALTER TABLE employee 
ADD FOREIGN KEY (super_id)
REFERENCES employee (emp_id)
ON DELETE SET NULL;

CREATE TABLE client (
    client_id INT PRIMARY KEY,
    client_name VARCHAR(40),
    branch_id INT,
    FOREIGN KEY (branch_id) REFERENCES branch(branch_id) ON DELETE SET NULL
);

CREATE TABLE works_with (
    emp_id INT,
    client_id INT,
    total_sales INT,
    PRIMARY KEY (emp_id, client_id), 
    FOREIGN KEY (emp_id) REFERENCES employee (emp_id) ON DELETE CASCADE,
    FOREIGN KEY (client_id) REFERENCES client(client_id) ON DELETE CASCADE
);

CREATE TABLE branch_supplier (
    branch_id INT, 
    supplier_name VARCHAR (40),
    supply_type VARCHAR(40),
    PRIMARY KEY (branch_id, supplier_name),
    FOREIGN KEY (branch_id) REFERENCES branch (branch_id) ON DELETE CASCADE
);

INSERT INTO employee VALUES (100, 'David', 'Wallace', '1967-11-17', 'M', 250000, NULL, NULL);

INSERT INTO branch VALUES (1, 'Corporate', 100, '2006-02-09');

我想更新 David Wallace,将branch_id 的外键设置为 1,将 emp_id 的外键设置为 100。我收到错误消息

“错误:无法添加或更新子行:外键约束失败('fun'。'employee',CONSTRAINT 'employee_ibfk_1' FOREIGN KEY('branch_id')引用'employee'('emp_id')ON DELETE SET NULL )

错误代码:ER_NO_REFERENCED_ROW_2

mysql foreign-keys popsql
1个回答
0
投票

你应该改变这个:

ALTER TABLE employee
ADD FOREIGN KEY (branch_id)
REFERENCES employee(emp_id)
ON DELETE SET NULL;

对此:

ALTER TABLE employee
ADD FOREIGN KEY (branch_id)
REFERENCES branch(branch_id)
ON DELETE SET NULL;
© www.soinside.com 2019 - 2024. All rights reserved.