创建一个数据库并设置表结构的例子,包括学生信息、考试成绩、班级信息和教师信息表,以及添加外键约束来关联表之间的数据
时间: 2024-09-12 17:07:30 浏览: 44
创建一个数据库并设置表结构,涉及几个核心元素:表格定义,主键和外键约束。这里是四个相关的表(学生信息、考试成绩、班级信息和教师信息)的一个示例:
1. 学生信息表(StudentInfo)
```sql
CREATE TABLE StudentInfo (
StuID INT NOT NULL AUTO_INCREMENT,
StuNumber VARCHAR(20) UNIQUE NOT NULL,
StuName VARCHAR(50) NOT NULL,
StuAge INT CHECK (StuAge >= 16 AND StuAge <= 35),
StuSex VARCHAR(10) DEFAULT 'male' NOT NULL CHECK (StuSex IN ('male', 'female')),
StuCard VARCHAR(18) UNIQUE,
StuJoinTime DATETIME NOT NULL,
StuAddress VARCHAR(50),
SClassID INT,
PRIMARY KEY (StuID),
FOREIGN KEY (SClassID) REFERENCES ClassInfo(ClassID)
);
```
2. 考试成绩表(StudentExam)
```sql
CREATE TABLE StudentExam (
ExamID INT NOT NULL AUTO_INCREMENT,
ExamNumber VARCHAR(100) UNIQUE NOT NULL,
EStuID INT NOT NULL,
ExamSubject VARCHAR(100) NOT NULL,
ExamResult INT CHECK (ExamResult BETWEEN 0 AND 100),
PRIMARY KEY (ExamID),
FOREIGN KEY (EStuID) REFERENCES StudentInfo(StuID)
);
```
3. 班级信息表(ClassInfo)
```sql
CREATE TABLE ClassInfo (
ClassID INT NOT NULL AUTO_INCREMENT,
ClassNumber VARCHAR(20) UNIQUE NOT NULL,
CTeacherID INT NOT NULL,
ClassGrade VARCHAR(10) NOT NULL DEFAULT 's1',
PRIMARY KEY (ClassID),
FOREIGN KEY (CTeacherID) REFERENCES TeacherInfo(TeacherID)
);
```
4. 教师信息表(TeacherInfo)
```sql
CREATE TABLE TeacherInfo (
TeacherID INT NOT NULL AUTO_INCREMENT,
TeacherName VARCHAR(50) NOT NULL,
TeacherTel VARCHAR(11) UNIQUE,
TeacherEmail VARCHAR(50) UNIQUE CHECK (teacherEmail LIKE '%@%.%'),
PRIMARY KEY (TeacherID)
);
```
以上每个表都包含了必要的字段,并通过`FOREIGN KEY`与其它表关联。例如,`StudentInfo`表的`SClassID`指向`ClassInfo`表的`ClassID`。
阅读全文