两个MySQL表之间的关系问题

时间:2019-03-05 12:56:17

标签: mysql datatable foreign-keys

如果表部分中的列管理器等于表section_id中的列section,我希望表部分中的列管理器将值自动设置为新添加的工作器的ID。 / p>

CREATE TABLE employee(
 emp_id INT AUTO_INCREMENT,
 name VARCHAR (30) NOT NULL,
 last_name VARCHAR (30) NOT NULL,
 position INT,
 section INT,
 PRIMARY KEY (emp_id));

CREATE TABLE section(
 section_id INT AUTO_INCREMENT,
 name VARCHAR (30) NOT NULL,
 manager INT,
 PRIMARY KEY (section_id));

CREATE TABLE position (
 position_id INT AUTO_INCREMENT,
 name VARCHAR (30) NOT NULL,
 PRIMARY KEY (position_id));

ALTER TABLE employee AUTO_INCREMENT = 1;
ALTER TABLE position AUTO_INCREMENT = 100;
ALTER TABLE section AUTO_INCREMENT = 1;

INSERT INTO section (name) VALUES ('lighting');
select * from section;
+------------+----------+---------+
| section_id | name     | manager |
+------------+----------+---------+
|          2 | lighting |    NULL |
+------------+----------+---------+

INSERT INTO employee (name, last_name, section) VALUES ('James', 'Bond', 2);

select * from section;
+------------+----------+---------+
| section_id | name     | manager |
+------------+----------+---------+
|          2 | lighting |    NULL |
+------------+----------+---------+

如何添加FOREIGN KEY,以便在添加James Bond时,节表中的列管理器会自动更改null to James Bond's id中的值?

0 个答案:

没有答案