1、创建成绩表,学号、课程号是外键,分数默认为0,限制在0-100之间 2、修改学生表结构,使其性别字段只能输入男或女两个字 3、删除学生表的记录时,级联删除成绩表中的相关记录 4、修改学生表的学号时,级联修改成绩表中的学号 5、系部表中增加学生人数字段,默认值为0
时间: 2023-06-11 11:06:52 浏览: 149
1.创建成绩表,包含学号、课程号、分数三个字段,其中学号和课程号为外键,分数默认为0,限制在0-100之间:
```sql
CREATE TABLE score (
id INT(11) NOT NULL AUTO_INCREMENT,
student_id INT(11) NOT NULL,
course_id INT(11) NOT NULL,
score INT(11) NOT NULL DEFAULT '0',
PRIMARY KEY (id),
FOREIGN KEY (student_id) REFERENCES student(id) ON DELETE CASCADE,
FOREIGN KEY (course_id) REFERENCES course(id) ON DELETE CASCADE,
CONSTRAINT score_range CHECK (score >= 0 AND score <= 100)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
```
2.修改学生表结构,使其性别字段只能输入男或女两个字:
```sql
ALTER TABLE student
MODIFY COLUMN gender ENUM('男', '女') NOT NULL;
```
3.删除学生表的记录时,级联删除成绩表中的相关记录:
```sql
ALTER TABLE score
ADD CONSTRAINT fk_student_score FOREIGN KEY (student_id) REFERENCES student(id) ON DELETE CASCADE;
```
4.修改学生表的学号时,级联修改成绩表中的学号:
```sql
ALTER TABLE score
DROP FOREIGN KEY fk_student_score;
ALTER TABLE student
CHANGE COLUMN id new_id INT(11) NOT NULL AUTO_INCREMENT;
ALTER TABLE score
CHANGE COLUMN student_id new_id INT(11) NOT NULL;
ALTER TABLE score
ADD CONSTRAINT fk_student_score FOREIGN KEY (new_id) REFERENCES student(new_id) ON DELETE CASCADE;
```
5.系部表中增加学生人数字段,默认值为0:
```sql
ALTER TABLE department
ADD COLUMN student_count INT(11) NOT NULL DEFAULT 0;
```
阅读全文