--1.6 FOREIGN KEY constraint -- Employee table CREATE TABLE Employee ( ID INT PRIMARY KEY, EmpName VARCHAR (20), Deptname VARCHAR-- department name ) INSERT into employee VALUES (1, ' Zhang San ', ' Software Development Department '); INSERT into Employee VALUES (2, ' John Doe ', ' Software Development Department '); INSERT into Employee VALUES (3, ' Harry ', ' Application Maintenance Department '); SELECT * from employee; -- Add employee, Department name data redundancy is high INSERT into Employee VALUES (4, ' Chen vi ', ' Software Development Department '); -- Solving the problem of high data redundancy: placing redundant fields in a separate table -- independent design of a departmental table CREATE TABLE Dept ( ID INT PRIMARY KEY, Deptname VARCHAR (20) ) DROP TABLE employee; -- Modify employee table CREATE TABLE Employee ( ID INT PRIMARY KEY, EmpName VARCHAR (20), DeptID INT,-- Change Department name to department ID -- declaring a foreign key constraint CONSTRAINT emlyee_dept_fk FOREIGN KEY (deptid) REFERENCES Dept (ID) on UPDATE CASCADE on DELETE CASCADE--on CASCADE updat E : Cascading modifications --FOREIGN key name foreign key reference table ( Reference field ) ) INSERT into Dept (id,deptname) VALUES (1, ' Software Development Department '); INSERT into Dept (Id,deptname) VALUES (2, ' Application Maintenance Department '); INSERT into Dept (Id,deptname) VALUES (3, ' Secretary '); INSERT into employee VALUES (1, ' Zhang San ', 1); INSERT into Employee VALUES (2, ' John Doe ', 1); INSERT into Employee VALUES (3, ' Harry ', 2); INSERT into Employee VALUES (4, ' Chen vi ', 3); -- problem : The record is not legal in business, employees insert a non-existent department data INSERT into employee VALUES (5, ' Chen vi ', 4);-- violation of FOREIGN KEY constraint: cannot add or update a child row:a Forei GN key Constraint fails (' DAY16 ', ' Employee ', constraint ' EMLYEE_DEPT_FK ' FOREIGN key (' DeptID ') REFERENCES ' dept ' (' ID ')) /c3> --1) When you have a FOREIGN key constraint, add the order of the data: Add the primary table first, and then add the secondary table data --2) When you have a FOREIGN key constraint, modify the order of the data: Modify the secondary table first, and then modify the main table data --3) When you have a foreign key constraint, delete the order of the data: delete the secondary table before deleting the main table data - -Modify the Department ( cannot directly modify the main Table ) UPDATE Dept SET id=4 WHERE id=3; -- Modify the employee table first UPDATE employee SET deptid=2 WHERE id=4; -- Delete Department DELETE from dept WHERE id=2; -- Delete the employee table first DELETE from employee WHERE deptid=2; SELECT * FROM Dept; SELECT * from employee; |