运用SQL语句创建相应的数据表,包含必要的完整性约束;
时间: 2024-03-22 11:38:31 浏览: 121
定义基本表续-sqldisanzhang
好的,以下是根据上面的关系模式,使用 SQL 语句创建相应的数据表,其中包含必要的完整性约束。
1. 读者(Reader)关系模式
```sql
CREATE TABLE Reader (
ReaderID INT PRIMARY KEY,
Name VARCHAR(50) NOT NULL,
Gender CHAR(1) NOT NULL,
Contact VARCHAR(20) NOT NULL
);
```
2. 借阅证(BorrowCard)关系模式
```sql
CREATE TABLE BorrowCard (
CardID INT PRIMARY KEY,
ReaderID INT NOT NULL,
CreateDate DATE NOT NULL,
ExpireDate DATE NOT NULL,
FOREIGN KEY (ReaderID) REFERENCES Reader(ReaderID) ON DELETE CASCADE
);
```
3. 图书(Book)关系模式
```sql
CREATE TABLE Book (
BookID INT PRIMARY KEY,
Title VARCHAR(100) NOT NULL,
Author VARCHAR(50) NOT NULL,
Press VARCHAR(50) NOT NULL,
Price DECIMAL(8,2) NOT NULL,
TotalNum INT NOT NULL,
CurrentNum INT NOT NULL,
CHECK (TotalNum >= CurrentNum)
);
```
4. 类别(Category)关系模式
```sql
CREATE TABLE Category (
CategoryID INT PRIMARY KEY,
Name VARCHAR(50) NOT NULL
);
```
5. 出版社(Press)关系模式
```sql
CREATE TABLE Press (
PressID INT PRIMARY KEY,
Name VARCHAR(50) NOT NULL
);
```
6. 借阅(Borrow)关系模式
```sql
CREATE TABLE Borrow (
CardID INT,
BookID INT,
BorrowDate DATE NOT NULL,
ReturnDate DATE,
PRIMARY KEY (CardID, BookID),
FOREIGN KEY (CardID) REFERENCES BorrowCard(CardID) ON DELETE CASCADE,
FOREIGN KEY (BookID) REFERENCES Book(BookID) ON DELETE CASCADE
);
```
7. 续借(Renew)关系模式
```sql
CREATE TABLE Renew (
CardID INT,
BookID INT,
RenewDate DATE NOT NULL,
NewReturnDate DATE NOT NULL,
PRIMARY KEY (CardID, BookID),
FOREIGN KEY (CardID) REFERENCES BorrowCard(CardID) ON DELETE CASCADE,
FOREIGN KEY (BookID) REFERENCES Book(BookID) ON DELETE CASCADE
);
```
8. 归还(Return)关系模式
```sql
CREATE TABLE Return (
CardID INT,
BookID INT,
ReturnDate DATE NOT NULL,
OverdueDays INT,
Fine DECIMAL(8,2),
PRIMARY KEY (CardID, BookID),
FOREIGN KEY (CardID) REFERENCES BorrowCard(CardID) ON DELETE CASCADE,
FOREIGN KEY (BookID) REFERENCES Book(BookID) ON DELETE CASCADE
);
```
9. 类别管理(Book_Category)关系模式
```sql
CREATE TABLE Book_Category (
BookID INT,
CategoryID INT,
PRIMARY KEY (BookID, CategoryID),
FOREIGN KEY (BookID) REFERENCES Book(BookID) ON DELETE CASCADE,
FOREIGN KEY (CategoryID) REFERENCES Category(CategoryID) ON DELETE CASCADE
);
```
10. 出版社管理(Book_Press)关系模式
```sql
CREATE TABLE Book_Press (
BookID INT,
PressID INT,
PRIMARY KEY (BookID, PressID),
FOREIGN KEY (BookID) REFERENCES Book(BookID) ON DELETE CASCADE,
FOREIGN KEY (PressID) REFERENCES Press(PressID) ON DELETE CASCADE
);
```
在上面的 SQL 语句中,我添加了一些完整性约束,如:
- 主键约束:每个表都有一个主键,用于唯一标识每个元组。
- 外键约束:一些表之间存在关联关系,使用外键约束来保持关联关系的完整性。
- 检查约束:对于某些属性,需要进行数据合法性检查,使用检查约束来保证数据的正确性。
如果您有其他的完整性约束需求,请告诉我,我会尽可能地满足您的需求。
阅读全文