阅读量:0
创建数据库 CREATE DATABASE IF NOT EXISTS CompanyDB; 使用数据库 USE CompanyDB; 创建员工表(Employees) CREATE TABLE IF NOT EXISTS Employees ( EmployeeID INT AUTO_INCREMENT PRIMARY KEY, FirstName VARCHAR(50), LastName VARCHAR(50), DepartmentID INT, CONSTRAINT fk_Department FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID) ON DELETE SET NULL ON UPDATE CASCADE ); 创建部门表(Departments) CREATE TABLE IF NOT EXISTS Departments ( DepartmentID INT AUTO_INCREMENT PRIMARY KEY, DepartmentName VARCHAR(100) ); 示例:插入部门数据 INSERT INTO Departments (DepartmentName) VALUES ('Human Resources'), ('Finance'), ('Marketing'); 示例:插入员工数据 INSERT INTO Employees (FirstName, LastName, DepartmentID) VALUES ('John', 'Doe', 1); INSERT INTO Employees (FirstName, LastName, DepartmentID) VALUES ('Jane', 'Smith', 2); INSERT INTO Employees (FirstName, LastName, DepartmentID) VALUES ('Alice', 'Johnson', 3);
SQL脚本执行后,将创建一个名为CompanyDB
的数据库,并在其中创建两个表:Departments
和Employees
。Employees
表中的DepartmentID
字段是一个外键,它引用了Departments
表中的DepartmentID
字段,外键约束设置为在删除父表中的记录时将子表中的对应字段设置为NULL(ON DELETE SET NULL
),并且在更新父表中的主键时,子表中的外键也会相应更新(ON UPDATE CASCADE
),脚本中还包含了插入示例数据的语句。