students(student_id, name, year, GPA, programs_code) instructors(instructor_id, name, title, salary, programs_code) programs(code, name, division, instructor_id) course(course_name, credit, domain, course_number) enroll(student_id, instructor_id, course_name) 1. Create tables according to the schema. 2. Use check or assertion to make sure instructors salary > 5000. 3. Use trigger to deal with cascade delete.
时间: 2024-02-02 15:05:15 浏览: 137
1. Here is the SQL code to create the tables according to the schema:
```
CREATE TABLE students (
student_id INT PRIMARY KEY,
name VARCHAR(50),
year INT,
GPA FLOAT,
programs_code VARCHAR(10)
);
CREATE TABLE instructors (
instructor_id INT PRIMARY KEY,
name VARCHAR(50),
title VARCHAR(50),
salary FLOAT,
programs_code VARCHAR(10),
CHECK (salary > 5000)
);
CREATE TABLE programs (
code VARCHAR(10) PRIMARY KEY,
name VARCHAR(50),
division VARCHAR(50),
instructor_id INT,
FOREIGN KEY (instructor_id) REFERENCES instructors (instructor_id) ON DELETE CASCADE
);
CREATE TABLE course (
course_name VARCHAR(50) PRIMARY KEY,
credit INT,
domain VARCHAR(50),
course_number INT
);
CREATE TABLE enroll (
student_id INT,
instructor_id INT,
course_name VARCHAR(50),
FOREIGN KEY (student_id) REFERENCES students (student_id) ON DELETE CASCADE,
FOREIGN KEY (instructor_id) REFERENCES instructors (instructor_id),
FOREIGN KEY (course_name) REFERENCES course (course_name)
);
```
2. The `CHECK` constraint has been added to the `instructors` table to ensure that the `salary` column is always greater than 5000. This will prevent any inserts or updates that would violate this rule.
3. Here is the SQL code to create a trigger that will handle cascade deletes:
```
CREATE TRIGGER delete_programs AFTER DELETE ON instructors
FOR EACH ROW
BEGIN
DELETE FROM programs WHERE programs.instructor_id = OLD.instructor_id;
END;
```
This trigger will be executed after a row is deleted from the `instructors` table. It will delete all rows from the `programs` table where the `instructor_id` matches the deleted row's `instructor_id`. This will ensure that there are no orphaned rows in the `programs` table when an instructor is deleted.
阅读全文